// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

last_event="";
	
	function hide_news(){
		document.getElementById(last_event).style.display='none';		
	}

	/*
function display_news(thenews, el) { 
		if(last_event!=""){
			document.getElementById(last_event).style.display='none';		
		}
		last_event=thenews;
	  //get the position of the placeholder element 
	  var pos = $(el).position(); 
	  var width = $(el).width(); 
	  //show the menu directly over the placeholder 
	  jQuery("#"+thenews).css( { "left": (pos.left + width-5) + "px", "top":(pos.top-55) + "px" } ); 
	  jQuery("#"+thenews).show(); 
	}
*/ 
	function display_news(thenews, el){
		if(last_event!=""){
			//document.getElementById(last_event).style.display='none';		
			$("#"+last_event).css("display","none");
		}
		last_event=thenews;
		//y=getOffset(el, 'y');
		//x=getOffset(el, 'x');
		
		document.getElementById(thenews).style.display='block';
		y=$(el).offset().top-(document.getElementById(thenews).offsetHeight/2)+(el.offsetHeight/2)+24;
		x=$(el).offset().left+15;
		document.getElementById(thenews).style.top=y+"px";
		document.getElementById(thenews).style.left=x+"px";
		
	}
	
	function viewCalendarEntry(doc_id,id,day,month,year){
		//load month via ajax
		var origPage = $.data(document.body,'origPage');
		if(origPage == null) origPage = doc_id;
		$.get('/ajax?snippet=CalendarDisplay&page='+origPage+'&cid='+doc_id+'&m='+month+'&y='+year,function(data){
			//alert(data);
			$("#calendar").replaceWith(data);
			$(".sectionPopup").colorbox({width:"700px", height:"450px", iframe:true, opacity:0.25, scrolling:false});
			
			if($.data(document.body,"sessionFlag") == "loggedin"){
			
				$("div.edit_b_h").each(function(index) {
					$(this).removeClass("edit_b_h").addClass("edit_b_v");
				});
			}
			
			$(".editIcon").button( { icons: {primary:'ui-icon-pencil'}, text: false } );
			$(".deleteIcon").button( { icons: {primary:'ui-icon-closethick'}, text: false } );
			
			
			//load element popup
			var element = $(".day-link:contains("+day+")")[0];
			display_news("day-popup-"+day, element);
		});	
	}

	

jQuery(document).ready(function(){

	if($("#whatsnew")[0]){
		
		$("#whatsnew .items div:even").each(function(){
			$(this).addClass("even");
		});
		$(".scrollable").scrollable({ vertical: true, circular: true }).autoscroll({ autoplay: true, interval: 6000 });
	}
	
	if($("#homedecor")[0]){
		
/*
		$("#homedecor .items div:even").each(function(){
			$(this).addClass("even");
		});
*/
		$(".scrollable2").scrollable({ vertical: false, circular: true }).autoscroll({ autoplay: true, interval: 4000 });
	}	


	if($("#map_info")[0]){
		var imgCount = 1;
		$('a.colorboxImage').live('click', function(e) {
			 // Live handler called.
			e.preventDefault();
			
			if($.browser.msie) window.open( $(this).attr("href"), "imgPopup", "status = 1, height = 600, width = 800, resizable = 0" );
			else $(this).colorbox();
		});
		$('a.prevImg').live('click', function(e) {
			 // Live handler called.
			e.preventDefault();
			if(imgCount > 1) imgCount--;
			else imgCount = 3;
			showImg(imgCount);
		});
		$('a.nextImg').live('click', function(e) {
			 // Live handler called.
			e.preventDefault();
			if(imgCount < 3) imgCount++;
			else imgCount = 1;
			showImg(imgCount);
		});
		
		function showImg(num){
			var src = $("#img"+num).attr("src");
			$("#img_display").attr("src",src);
			
			var link = src.replace("t_","");
			$("#img_link").attr("href",link);
		}
	}


	//fix menu width (last element)
	if($('ul.topnav li a.last').parent().position()){
		var menuWidth = $('ul.topnav').width();
		var posLast = $('ul.topnav li a.last').parent().position().left;
		
		var lastWidth = menuWidth - posLast;
		
		var elWidth = $('ul.topnav li a.last').width();
		
		var newPadding = ((lastWidth - elWidth) / 2) -1;
		
		$('ul.topnav li a.last').css('padding-left',newPadding+'px');
		$('ul.topnav li a.last').css('padding-right',newPadding+'px');
	}
	
	//tooltip for contextual help
	$('.tooltip').qtip({
	position: {
      corner: {
         target: 'topRight',
         tooltip: 'bottomLeft'
      }
    },
	style: { 
      width: 240,
      padding: 10,
      background: '#FFFFFF',
      color: 'black',
      textAlign: 'left',
      border: {
         width: 3,
         radius: 5,
         color: '#4F91CD'
      },
      tip: "bottomLeft",
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }})
   
   //tooltip for contextual help
	$('.tooltipPopup.bottom').qtip({
	position: {
      corner: {
         target: 'bottomMiddle',
         tooltip: 'topMiddle'
      }
    },
	style: { 
      width: 280,
      padding: 10,
      background: '#FFFFFF',
      color: 'black',
      textAlign: 'left',
      border: {
         width: 3,
         radius: 5,
         color: '#4F91CD'
      },
      tip: "topMiddle",
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }})
   
   $('.tooltipPopup.top').qtip({
	position: {
      corner: {
         target: 'topMiddle',
         tooltip: 'bottomMiddle'
      }
    },
	style: { 
      width: 280,
      padding: 10,
      background: '#FFFFFF',
      color: 'black',
      textAlign: 'left',
      border: {
         width: 3,
         radius: 5,
         color: '#4F91CD'
      },
      tip: "bottomMiddle",
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }})
   
   //tooltip for contextual help (buttons)
   $('.tooltipbtn').qtip({
	position: {
      corner: {
         target: 'bottomMiddle',
         tooltip: 'topMiddle'
      }
    },
	style: { 
      width: 240,
      padding: 10,
      background: '#FFFFFF',
      color: 'black',
      textAlign: 'left',
      border: {
         width: 3,
         radius: 5,
         color: '#4F91CD'
      },
      tip: "topMiddle",
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }})
   
	   
	//alternating row colors for tables:
	$('table.business-list-admin tr:odd td').not(".analytics-row td").css({backgroundColor: '#E2E9EE'});
	$('table.analytics-sources-table tr:even td').css({backgroundColor: '#E2E9EE'});
	
	$('table.news-list tr:odd td').css({backgroundColor: '#F2F4F6'});
	
	//linking of rows and hover
	$("table.business-list tbody tr").hover(function (){
		$(this).addClass("hover");
	},
	function () {
		$(this).removeClass("hover");
	});
	
	$("table.business-list tbody tr").click(function(){
	 window.location = '/'+$(this).find("a").attr("href");
	});
	
	//tablesorter custom widgets:
	 $.tablesorter.addWidget({
	    // give the widget an id
	    id: "sortPersist",
	    // format is called when the on init and when a sorting has finished
	    format: function(table) {
	

	      // Cookie info
	      var cookieName = 'OOP_SORT_COOKIE_V3';
	      var cookie = $.cookie(cookieName);
	      var options = {path: '/'};
	
	      var data = {};
	      var sortList = table.config.sortList;
	      var tableId = $(table).attr('id');
	      var cookieExists = (typeof(cookie) != "undefined" && cookie != null);
	
	      // If the existing sortList isn't empty, set it into the cookie and get out
	      if (sortList.length > 0) {
	        if (cookieExists) {
	          data = $.evalJSON(cookie);
	        }
	        data[tableId] = sortList;
	        $.cookie(cookieName, $.toJSON(data), options);
	      }
	
	      // Otherwise...
	      else {
	        if (cookieExists) { 
	
	          // Get the cookie data
	          var data = $.evalJSON($.cookie(cookieName));
	
	          // If it exists
	          if (typeof(data[tableId]) != "undefined" && data[tableId] != null && data[tableId] != "") {
	
	            // Get the list
	            sortList = data[tableId];
	            //console.log(sortList[0][0]);
	            var targetCol = sortList[0][0];
	            var cols = $(table).children("thead").children("tr").children("th").length;
				
	            // And finally, if the list is NOT empty, trigger the sort with the new list
	            if (sortList.length > 0) {
	            
	              //check if target column exists
	              if(targetCol < cols){
	              	$(table).trigger("sorton", [sortList]);
	              }
	            }
	          }
	        }
	      }

	    }
	  });
	
	//tablesorter:
	
	$("table.business-list.businesses")
	.tablesorter({widthFixed: true, widgets: ['zebra','sortPersist'] }) 
    .tablesorterPager({container: $(".pager.businesses") });
    
    $("table.business-list.products")
	.tablesorter({widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.products")});
    
    $("table.business-list.services")
	.tablesorter({widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.services")});
 
    
    $("table.business-list.jobs")
	.tablesorter({
		headers:{
			4: { sorter: "usLongDate" }
		},
		widthFixed: true,
		widgets: ['zebra','sortPersist'],
		sortList: [[4,1]] })
    .tablesorterPager({container: $(".pager.jobs")});
    
    $("table.business-list.rfps")
	.tablesorter({
		headers:{
			2: { sorter: "usLongDate" }
		},widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.rfps")});
    
    $("table.business-list.investments")
	.tablesorter({widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.investments")});
    
    $("table.business-list.news")
	.tablesorter({
		headers:{
			2: { sorter: "usLongDate" }
		},widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.news")});
    
    $("table.business-list.events")
	.tablesorter({
		headers:{
			2: { sorter: "usLongDate" }
		},widthFixed: true, widgets: ['zebra','sortPersist']}) 
    .tablesorterPager({container: $(".pager.events")});
    
    //tablesorter pager change
    $(".pagesize").change(function(){
    	//log('changed to: '+$(this).val());
    	setPagerVal(true);
    });
	
	//tabs
	$("#tabs").css("left","0px");
	$('#tabs').tabs({ cookie: {} }); //load with cookie option - restores previous tab
	
	//dialog box in iframe
	$('.dialog-link').click(function(e) {
            e.preventDefault();
            var $this = $(this);
            var horizontalPadding = 30;
            var verticalPadding = 30;
            $('<iframe id="externalSite" class="externalSite" src="' + this.href + '" scrolling="no"></iframe>').dialog({
                title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
                autoOpen: true,
                width: 800,
                height: 500,
                modal: true,
                resizable: true,
                autoResize: true,
                overlay: {
                    opacity: 0.5,
                    background: "black"
                }
            }).width(800 - horizontalPadding).height(500 - verticalPadding);            
        });
	
	//section popup (colorbox)
	//$(".sectionPopup").colorbox({width:"700px", height:"450px", iframe:true, opacity:0.25, scrolling:false});
	//$(".sectionPopupTall").colorbox({width:"700px", height:"600px", iframe:true, opacity:0.25, scrolling:false});
	
	//rollover images
	$("img.rollover").hover(
		function()
		{
		this.src = this.src.replace("_out","_ovr");
		},
		function()
		{
		this.src = this.src.replace("_ovr","_out");
		}
	);
	
	//select search query in search box
		var kw = $(document).getUrlParam("kw");
		if(kw){
			kw = decodeURIComponent(kw.replace(/\+/g," "));
		}
		
		var search_type = $(document).getUrlParam("search_type");
		var category = $(document).getUrlParam("category");
		var area = $(document).getUrlParam("area");
		var location = $(document).getUrlParam("location");
		if(location){
			location = decodeURIComponent(location.replace(/\+/g," "));
		}
		
		if(kw != null) $("#kw").attr("value",kw);
		$("#search_type option[value='"+search_type+"']").attr("selected", "selected");
		$("#category option[value='"+category+"']").attr("selected", "selected");
		$("#area option[value='"+area+"']").attr("selected", "selected");
		if(location != null) $("#location").attr("value",location);
		
	
	//jQuery UI buttons:
	$("input:submit, input:reset").button();
	$(".submitBtn").button();
	
	//custom buttons:
	$(".editBtn").button( { icons: {primary:'ui-icon-pencil'} } );
	$(".deleteBtn").button( { icons: {primary:'ui-icon-closethick'} } );
	$(".adminBtn").button( { icons: {primary:'ui-icon-person'} } );
	$(".addbusinessBtn").button( { icons: {primary:'ui-icon-plusthick'} } );
	
	$(".statsBtn").button( { icons: {primary:'ui-icon-signal'} } );
	$(".updateBtn").button( { icons: {primary:'ui-icon-refresh'} } );
	
	$(".addadminLink").button( { icons: {primary:'ui-icon-plusthick'} } );
	$(".editLink").button( { icons: {primary:'ui-icon-pencil'} } );
	
	$(".editIcon").button( { icons: {primary:'ui-icon-pencil'}, text: false } );
	$(".deleteIcon").button( { icons: {primary:'ui-icon-closethick'}, text: false } );
	
	//form masking
	$("#b_phone").mask("(999) 999-9999? x99999");
	$("#b_fax").mask("(999) 999-9999");
	$("#createbusinessfrm #b_zip").mask("a9a 9a9");
	
	//business_page scripts

	jQuery(".section").hide();
	jQuery(".section:first").slideToggle(0);
	
	if($("#head_red").length){
		triggerSection($("#head_red"),0); //show red
	}
	
	var open = $(document).getUrlParam("open");
	if(open != null){
		if($.data(document.body,"sessionFlag") != "loggedin"){
			if(open != "red") triggerSection($("#head_"+open),1000);
		}
		setTimeout('$.scrollTo($("#head_'+open+'"),1000)',1000);
	}
	
	var loc = $(document).getUrlParam("loc");
	if(loc != null){ 
		setTimeout('$.scrollTo($("#'+loc+'"),1000)',1000);
	}
	
	//toggle the componenet with class msg_body
	jQuery(".section_head").click(function(){ triggerSection($(this), 0, true) });
	
	
	//back to top link
	$('a.top').click(function(){
	     $('html, body').animate({scrollTop: '0px'}, 300);
	     return false;
	});
	
		
	//multi-select
	//$(".multiselect").multiselect();
	//$(".multiselect").multiselect({sortable: false});
	
	//accordion
	$("#resources-accordion").css("left","0px");
	$("#resources-accordion").accordion({
			autoHeight: false,
			navigation: true
		});

	$("#createBusiness-accordion").css("left","0px");
	/*
$("#createBusiness-accordion").accordion({
			autoHeight: false,
			navigation: true
		});	
*/

	$(".statsBtn").each(function(){
		$(this).click(function(){
			var tmp = $(this).attr("id").split("statsBtn");
			var rowId = tmp[1];
			if($(this).button( "option", "label") == "Show Statistics") $(this).button( "option", "label","Hide Statistics");
			else $(this).button( "option", "label","Show Statistics");
			
			$("#analyticsRow"+rowId).toggle();
		});
	});

	$(".updateBtn").each(function(){
		$(this).click(function(){	
			var target = $(this).parent().parent().children(".data_container");
			
			var pageurl = $(this).parent().parent().children(".pageurl").val();
			var startdate = $(this).parent().parent().children(".date_container").children(".start_date").val();
			var enddate = $(this).parent().parent().children(".date_container").children(".end_date").val();
			
			var submitData = 'pageurl='+pageurl+'&start_date='+startdate+'&end_date='+enddate;
			
			target.html('<div class="analytics-loading"><p>Loading new data, please wait...</p></div>');
			
			$.get('/assets/snippets/business/ajax.analytics.php', submitData, function(data) {
				target.html(data);
			});
		});
	});
	
});

function isIE()
{
return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function triggerSection(el, delay, click)
	{
		$img=jQuery(el).find('img');
		src=$img.attr('src');
		$span=jQuery(el).find('span');
		
		if(src.match('_up.png')) { 
		    $img.attr('src', src.replace('_up.png', '_down.png'));
		    $span.html('show');
		} else if (src.match('_down.png')) { 
		    $img.attr('src', src.replace('_down.png', '_up.png')); 
		    $span.html('hide');
		} 
		
		$(el).next(".section").delay(delay).slideToggle(500);
		if(!click && el.attr('id') != $("#head_red").attr('id')) triggerSection($("#head_red"),500);
	}
	
//tablesorter pager functions

function setPagerVal(set){
	// Cookie info
	var cookieName = 'OOP_PAGER_ROWS';
	var cookie = $.cookie(cookieName);
	var options = {path: '/'};
	
	var pagerVal = $(".pagesize").val();
	var cookieExists = (typeof(cookie) != "undefined" && cookie != null);
	
	if(cookieExists && !set){
		//set pager to cookie value
		$(".pagesize").val($.cookie(cookieName));
		$(".pagesize").change();
	} else {
		// set cookie
		$.cookie(cookieName, pagerVal, options);
	}
}


	
/*
function multiselectAdded(itemText){
	//check for non profit
	if(itemText.indexOf("Not for Profit") > -1){
		$(".nonprofit").show();
		$(".multiselect-np").multiselect({sortable: false});
		$("#nonprofit").addClass("required");
	}

}

function multiselectRemoved(){
	setTimeout("triggerRemoveField()",500);
}
function triggerRemoveField(){
	var itemText = $("ul.selected li.ui-element").text();
	//check for non profit
	if(itemText.indexOf("Not for Profit") == -1){
		$(".nonprofit").fadeOut();
		
		//delete values for fields:
		$("#nonprofit").val("");
		$("#nonprofit").removeClass("required");
		$("#resource_type").val("");
	}
}
*/


	
	/*
	function display_news(thenews, el){
		if(last_event!=""){
			document.getElementById(last_event).style.display='none';		
		}
		last_event=thenews;
		//y=getOffset(el, 'y');
		//x=getOffset(el, 'x');
		document.getElementById(thenews).style.display='block';
		y=el.offsetTop-(document.getElementById(thenews).offsetHeight/2)+(el.offsetHeight/2)+24;
		x=el.offsetLeft+15;
		//alert("x="+x+" y="+y);
		document.getElementById(thenews).style.top=y+"px";
		document.getElementById(thenews).style.left=x+"px";
		
	}
	*/
/*
$j(document).ready(function() {
	//Search "enter" key:
	$j('#ajaxSearch_form').keyup(function(e) {
		//alert(e.keyCode);
		if(e.keyCode == 13) {
			location.href = "search-results.html?AS_search="+document.getElementById('ajaxSearch_input').value;
		}
	});
	
	//display active image	
	var tmp = $j('img.active').attr("src");
	tmpArr = tmp.split(".");
	$j('img.active').attr("src", tmpArr[0]+"-ovr"+"."+tmpArr[1]);
	
	//prevent mouseout from changing img
	var tmp2 = $j('img.active').attr("onmouseout");
	tmp2Arr = tmp.split(".");
	$j('img.active').attr("onmouseout", tmpArr[0]+"-ovr"+"."+tmpArr[1]);
});
*/
