// no more undefined object "console" errors:
if(typeof(console) === 'undefined') {
    var console = {}
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

//Date functions
function padzero(n) {
	return n < 10 ? '0' + n : n;
}
function pad2zeros(n) {
       if (n < 100) {
           n = '0' + n;
       }
       if (n < 10) {
           n = '0' + n;
       }
       return n;     
}
function toISOString(d) {
       return d.getUTCFullYear() + '-' +  padzero(d.getUTCMonth() + 1) + '-' + padzero(d.getUTCDate()) + 'T' + padzero(d.getUTCHours()) + ':' +  padzero(d.getUTCMinutes()) + ':' + padzero(d.getUTCSeconds()) + 'Z';
   }

function ISOFromTimestamp(timestamp) {
	var dt = new Date(timestamp * 1000);
	return toISOString(dt);
}

function getDate(timestamp,type, force) {
	var d = new Date(timestamp * 1000);
	var now = new Date();
	var diff = now - d;
	diff = Math.round(diff/1000/60/60/24);
	var output = '';
	
	if (diff < 365 || force == true) {
		if (d.getDay() == 0) output += 'Sun, ';
		if (d.getDay() == 1) output += 'Mon, ';
		if (d.getDay() == 2) output += 'Tues, ';
		if (d.getDay() == 4) output += 'Wed, ';
		if (d.getDay() == 5) output += 'Thur, ';
		if (d.getDay() == 6) output += 'Fri, ';

		if (d.getMonth() == 0) output += 'Jan';
		if (d.getMonth() == 1) output += 'Feb';
		if (d.getMonth() == 2) output += 'Mar';
		if (d.getMonth() == 3) output += 'Apr';
		if (d.getMonth() == 4) output += 'May';
		if (d.getMonth() == 5) output += 'June';
		if (d.getMonth() == 6) output += 'July';
		if (d.getMonth() == 7) output += 'Aug';
		if (d.getMonth() == 8) output += 'Sept';
		if (d.getMonth() == 9) output += 'Oct';
		if (d.getMonth() == 10) output += 'Nov';
		if (d.getMonth() == 11) output += 'Dec';

		output += ' ' + d.getDate();

		if (type == 'full') {
			output += ', ' + d.getFullYear();

			var hours = d.getHours();
			var pm = false;
			if (hours > 12) {
				hours = hours - 12;
				pm = true;
			}
			output += ' at ' + hours + ':';
			if(String(d.getMinutes()).length == 1) { output += '0'; }
			output += d.getMinutes();
			if (pm == true) {
				output += ' PM';
			} else {
				output += ' AM'
			}
		} else {

		}
	} else {
		var month = d.getMonth() + 1;
		output += month + '/' + d.getDate() + '/' + d.getFullYear();
	}

	return output;
}


function get_cookies_array() {

    var cookies = new Array();

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies.push({'key':decodeURIComponent(name_value[0]),'value':decodeURIComponent(name_value[1])});
        }
    }

    return cookies;
   
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

$(document).ready(function(){
	//External Links
	$('a[rel=external]').click(function(e) {
	  window.open($(this).attr('href'));
	  e.preventDefault();
	});
	
	//Generic toggle
	$('.toggle').click(function(){
		$("#"+$(this).attr('rel')).toggle();
		return false;
	})
	
	//Custom select generator
	
	var selects = [];
	var selectCounter = 0;
	$('select').not('.normal').each(function(i){
		var buildItem = [];
		buildItem['cssclass'] = $(this).attr("class");
		buildItem['id'] = $(this).attr("id");
		buildItem['name'] = $(this).attr("name");
		buildItem['type'] = $(this).attr("rel");
		var children = [];
		var selected = '';
		$(this).children('option').each(function(x){	
			var child = [];
			child['value'] = $(this).val();
			child['text'] = $(this).text();
			children.push(child);

			if ($(this).attr('selected'))
				selected = child;


		});
		buildItem['options'] = children;
		selects.push(buildItem);

		if (selected.value == undefined) {
			selected = buildItem.options[0];
		}
		
		//Standard duplication of select box
		//Standard: Works just like a select box
		//Standard-link: Works like a drop-down link menu
		
		if (buildItem.type == '' || !buildItem.type || buildItem.type === undefined)
			buildItem.type = 'standard';
		if (buildItem.type == 'standard' || buildItem.type == 'standard-link') {
			buildCode = "<div class='" + buildItem.cssclass + " bm-select standard' id='" + buildItem.id + "' rel='"+buildItem.type+"'>";
			buildCode += "<a id='select-action-"+selectCounter+"' class='bmdrop' href='#' rel='select-menu-"+selectCounter+"'><span class='text'>"+selected.text+"</span><span class='graphic'>&nbsp;</span></a>";
			buildCode += "<ul id='select-menu-"+selectCounter+"' class='bmselect-menu'>";
			for (var y=0; y < buildItem.options.length; y++) {
				
				//don't make it a link if this option doesn't have a value. Hide it if this is the default selection...
				if (buildItem.options[y].value == "" || !buildItem.options[y].value || buildItem.options[y].value == null) {
					if (buildItem.options[y].value != selected.value)
						buildCode += "<li class='non-option'>"+buildItem.options[y].text+"</li>";
				} else {
				//Different outputs for different select box types
					if (buildItem.type == 'standard-link') {
							buildCode += "<li><a href='"+buildItem.options[y].value+"' class='select-standard-item' rel='"+selectCounter+"'>"+buildItem.options[y].text+"</a></li>";
					} else {
						buildCode += "<li rel='"+buildItem.options[y].value+"'><a href='#' class='select-standard-item' rel='"+selectCounter+"'>"+buildItem.options[y].text+"</a></li>";
					}
				
				}
			
			}
			buildCode += "</ul>";
			buildCode += "<input id='input-value-"+selectCounter+"' name='"+buildItem.name+"' type='hidden' value='"+selected.value+"'/>";
			buildCode += "</div>";
		}
		
		$(this).replaceWith(buildCode);
		
		selectCounter++;
	});	
	
	
	//Custom Drop-down code
	var dropDowns = new Array();
		
	$('.bmdrop').click(function() {
		
		var target = $(this).attr('rel');
		
		if ($('#'+target).css('display') == 'none') {
			hideDropdowns();
			$('#'+target).toggle();
		} else {
			$('#'+target).toggle();
		}
			
		dropDowns.push(target);
		
		return false;

	});
	
	var selectRegistry = [];
	$('.bm-select a.bmdrop').click(function(){
		if (!selectRegistry[$(this).attr("rel")]) {
			var boxPosition = $("#"+$(this).attr("rel")).offset({relativeTo: "body"}).left;
			var leftPosition = $(this).offset({relativeTo: "body"}).left;
			var offset = $("#"+$(this).attr("rel")).css('left');
			offset = Number(offset.replace(/px/i,""));
			var toGo = Math.floor(leftPosition - boxPosition);	
			var marginLeft = $("#"+$(this).attr("rel")).css('margin-left');
			marginLeft = Number(marginLeft.replace(/px/i,""));
			$("#"+$(this).attr("rel")).css('left',toGo+marginLeft+offset);
		}
		selectRegistry[$(this).attr("rel")] = true;
		return false;
	});
	
	$('.select-standard-item').click(function(){
		
		if ($(this).parents('div.bm-select').attr('rel')=='standard') {	
			var targetId = $(this).attr('rel');
			$("#select-menu-"+targetId).toggle();
			$("#input-value-"+targetId).val($(this).parent().attr("rel"));
			$("#select-action-"+targetId+" .text").text($(this).text());
			dropDowns.push("select-menu-"+targetId);
			$(this).parents('div.bm-select').change();
			return false;
		}
	});
	
	$('body').click(function(){
		hideDropdowns();
	});
	
	function hideDropdowns() {
		var target;
		for(var i=0; i<dropDowns.length; i++) {
			target = dropDowns[i];
			$("#"+target).hide();
		}
		dropDowns = new Array();
	}
	
	//accordion	
	$('.accordion').hide();
	
	//Get previously opened panel
	theCookies = get_cookies_array();
	var foundMatches = false;
	for (var i=0; i < theCookies.length; i++) {
		if(theCookies[i].key.match('accordion-')) {
			$('#'+theCookies[i].value).addClass('default');
			$('.accordion h3 a[rel='+theCookies[i].value+']').parent('h3').addClass('current');
			foundMatches = true;
		}
	}
	//open up first panel if none previously visisted
	if (!foundMatches) {
		$('.accordion').children('ul.panel:first').addClass('default');
		$('.accordion').children('h3:first').addClass('current');
	}
	
	//hide all panels that are not set to be opened.
	$('.panel:not(.default)').hide();
	
	$('.accordion').show();
	
	$('.accordion h3 a').click(function(){
		
		var theParent = $(this).parents('.accordion');
		var currentPanel = $(this).attr('rel');
	
	
		$('.accordion h3').removeClass('current');
		$(this).parent('h3').addClass('current');	
		$('#'+currentPanel).slideDown();
		theParent.children('.panel[id!='+currentPanel+']').slideUp();
		
		
		//set session cookie
		if (theParent.attr('id')) {
			document.cookie = theParent.attr('id') + '=' + currentPanel + '; path=/';
		}
		
		$(this).blur();
		return false;
	});
	
	
	//drop-down SEARCH
	$('.search-box input').focus();
	$('.search-box input').select();
	
	
	var searchType = 'all';
	var hasFocus = false;
	if($('#search-type-adv').val() == 0) {
	  $('#search-type-select').click(function() {
		$('#search-type-dropdown').toggle();
		$(this).blur();
		return false;
	  });
	}
	
	$('.search-type-option').click(function(){
		var thevalue = $('.search-box input').attr('value');
		if (thevalue.length >= 1) {
			$('#search-form').submit();
		} else {
			$('#search-type-dropdown').hide();
		}
		return false;
	});
	
	$('.search-type-option').hover(function(){
		searchType = $(this).attr('rel');
		$('#search-type-data').attr('value',searchType);
		$('.search-type-text').text($(this).text());
	})

	$('.search-type-text').click(function(){
		if($('.search-box input').val() != '')
			$('#search-form').submit();

		return false;
	});
	
	$('body').click(function(){
		$('#search-type-dropdown').hide();
	});
	
	$('.search-box input').focus(function() {
		hasFocus = true;
	});
	
	$('.search-box input').blur(function() {
		hasFocus = false;
	});
	
	$(document).keypress(function(e){
		if (hasFocus && e.which == 13) {
			var thevalue = $('.search-box input').attr('value');
			if (e.which == 13 && thevalue.length >= 1) {
				$('#search-form').submit();
			} else {
				$('#search-type-dropdown').hide();
				return false;	
			}
		}	
	});
	
	
	//Advanced Search
	if ($("input[name='topical']:checked").val() == 'false')
		$('#as-topic-field').show();
	else
		$('#as-topic-field').hide();
	
	var search_text = 'Search All';
	$('#advanced-search-toggle').click(function(){
		$('.advanced-search-box').toggle();
		if($(this).attr('class') == 'advanced-search-close') { $(this).attr('class', 'advanced-search'); }
		else if($(this).attr('class') == 'advanced-search') { $(this).attr('class', 'advanced-search-close'); }
		if ($(this).hasClass('advanced-search-close')) {
			search_text = $('a.search-type-text').text();
			$('a.search-type-text').text('Advanced Search');
			if($('#search-type-adv')) { $('#search-type-adv').val('1'); }
			$('#search-type-select').unbind('click');
			$('#search-type-container').attr('class', 'search-type-disabled rounded-small');
			
		}	
		else {
			$('a.search-type-text').text(search_text);	
			if($('#search-type-adv')) { $('#search-type-adv').val('0'); }
			$('#search-type-select').click(function() {
				$('#search-type-dropdown').toggle();
				$(this).blur();
				return false;
			});
			$('#search-type-container').attr('class', 'search-type rounded-small');
		}
			
		return false;
	});
	
	$("input[name='topical']").change(function(){
		if ($("input[name='topical']:checked").val() == 'false')
			$('#as-topic-field').show();
		else
			$('#as-topic-field').hide();
	});
	
	$(".checkbox-group-all").click(function() {
		$("#"+$(this).attr('rel') + " input").each(function(i) {
			$(this).attr('checked','checked');
		});
		return false;
	});
	$(".checkbox-group-none").click(function() {
		$("#"+$(this).attr('rel') + " input").each(function(i) {
			$(this).attr('checked',false);
		});
		return false;
	});
	
	
	//Likes Dislikes widget
	var meterColor = "#6ebc25";
	var voteMeterLength = 60;
	var votePercentage = Number($('#like-meter-rating').val());
	if (votePercentage < 65)
		meterColor = "#eebc25";
	if (votePercentage < 30)
		meterColor = "#d42723";
	var voteMeter = votePercentage * (voteMeterLength/100);
	$('.like-meter').append("<div class='meter-container' style='width:" + voteMeterLength + "px'><div class='meter' style='width:" + voteMeter + "px; background-color:" + meterColor +"'><\/div><\/div>");
	
});

