var COUNT=0;
var jQ=null;

$.noConflict();
jQuery(document).ready(function($) {

	jQ=$;

	calendar_categories_init();
	calendar_init();
	
	// Swap form field values when focused
	$('#site-search input[type="text"], #subscribe input[type="text"]').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {this.value = '';}
		});
		$(this).blur(function() {
			if(this.value == '') {this.value = default_value;}
		});
	});
	
	
	// Toggle the social box in sidebar
	$('#social-connect ul li a').click(function() {
		var showBox = $(this).attr('href').replace('#', '');
		
		$('#'+showBox).show();
		$('#social-connect .box').not('#'+showBox).hide();
		
		return false;
	});
	
	
	// Slideshow on home page
	$('#primary ul.slides').cycle({
		fx: 'fade',
		timeout: 5000,
		activePagerClass: 'active',
		prev: '#main-feature-controls .prev a',
		next: '#main-feature-controls .next a',
		pager: '#main-feature-nav'
	});
		
		
	// Show browser print window for post/page sharing tool
	$('ul.post-actions li.print a').click(function() {
		window.print();
		return false;
	});
		
		
	// Slideshow on posts/pages
	$('#post-content .gallery').cycle({
		fx: 'fade',
		timeout: 5000,
		containerResize: 1,
		fit: 1
	});

	$('select.affects_provinces').change(function() {
		var countryID=$(this).find('option:selected').attr('value');
		$.getJSON("/ajax/get-provinces.php",{c:countryID},function(d,status,xobj) {
			var opts='';
			for (i=0;i<d.length;i++) opts+='<option value="'+d[i].replace('"','&quot;')+'">'+d[i]+'</option>';
			if (d.length==0) opts='<option value="">n/a</option>';
			$('select.provinces').html(opts);
		});
	});

	$('select.affects_location').change(function() {
		var divs=["__LabelAddressInfo","es_location_venue","es_location_street","es_location_street2","es_location_city","es_location_postal","es_location_country","es_location_province"];
		var locationID=$(this).find('option:selected').attr('value');
		if (locationID=="new") for (var i=0;i<divs.length;i++) $("#fr_"+divs[i]).show();
		else for (var i=0;i<divs.length;i++) $("#fr_"+divs[i]).hide();
	});

	var textblocks=$("textarea.limited");
	for (var i=0;i<textblocks.length;i++) limitedtext_initialize(textblocks[i]);

	var multidates=$(".multidate");
	for (var i=0;i<multidates.length;i++) multidate_initialize(multidates[i]);

	var phoneblocks=$(".phone3,.phone4,.phoneExt");
	for (var i=0;i<phoneblocks.length;i++) phonetext_initialize(phoneblocks[i]);

	// Decode encrypted blocks of text
	var encDivs = $('.jsNeeded');
	for (var i=0; i<encDivs.length; i++) {
		var encoded = $(encDivs[i]).attr('data-enc');
		eval(rot13(unescape(encoded)));
		$(encDivs[i]).html(decoded);
	}

});

function phonetext_initialize(o) {

	// ensure numbers only...
	jQuery(o).keypress(function(e) {
		var ch=e.charCode?e.charCode:e.keyCode?e.keyCode:e.which;
		if ((ch==8)||(ch==9)||(ch==16)||(ch==37)||(ch==39)||(ch==46)||(ch==17)||(ch==35)||(ch==36)||(ch==45)) return true;

		return /^(\d)$/.test(String.fromCharCode(ch));
	});

	// switch focus to next box if needed...
	jQuery(o).keyup(function(e) {
		var ch=e.keyCode?e.keyCode:e.charCode?e.charCode:e.which;
		if (!((ch==8)||(ch==9)||(ch==16)||(ch==37)||(ch==39)||(ch==46)||(ch==17)||(ch==35)||(ch==36)||(ch==45))) {
			var l=jQuery(this).hasClass("phone3")?3:4;
			if (jQuery(this).attr("value").length==l) {
				var nextField=jQuery(this).attr("data-next");
				if (nextField!="") {
					jQuery("#"+nextField).focus();
				}
			}
		}
		return false;
	});
}

function calendar_categories_init() {

	// Toggle event categories on sidebar calendar
	jQ('#category-select #toggle-cat').click(function() {
		jQ('#events-calendar .popup').hide();
		jQ(this).toggleClass('active').parent().find('ul').toggle();
		return false;
	});

	jQ('#category-select ul li a').click(function() {
		
		//if (jQ(this).parent().hasClass('all')) {
			// set active and de-activate the other LIs...
			
			//var current_cat = jQ(this).text().replace(' + ', '-').toLowerCase();
			
			jQ(this).parent().parent().find('li').removeClass('active');
			jQ(this).parent().addClass('active');
			//jQ('#calendar thead').attr('class', current_cat);
		/*
		}
		else {
			jQ(this).parent().toggleClass('active');

			if (jQ(this).parent().hasClass('active')) {
			// must de-activate the 'all' LI...

				jQ('#category-select ul li.all').removeClass('active');
			}
			else {
			// in case no LIs are active, re-activate the 'all' LI...

				LIs=jQ(this).parent().parent().find('li.active');
				if (LIs.length==0) {
					jQ('#category-select ul li.all').addClass('active');
				}
			}
		}
		*/

		cList=[];
		LIs=jQ('#category-select ul li.active');
		for (i=0;i<LIs.length;i++) {
			cID=jQ(LIs[i]).attr("data-cid");
			if ((cID!="")&&(cID>0)) cList.push(cID);
		}
		curDate=jQ('#events-calendar .month-select').attr("data-curdate");

		jQ('#calendar-wrap').load('/wp-content/themes/inthehills/ajax/calendar-events.php #calendar',{d:curDate,categories:cList},function(text,status,x) {
			jQ('#category-select #toggle-cat').toggleClass('active').parent().find('ul').toggle();
			calendar_init();
		});

		return false;
	});
}

function calendar_init() {

	jQ('#events-calendar .month-select a').click(function() {

		cList=[];
		LIs=jQ('#category-select ul li.active');
		for (i=0;i<LIs.length;i++) {
			cID=jQ(LIs[i]).attr("data-cid");
			if ((cID!="")&&(cID>0)) cList.push(cID);
		}

		jQ('#calendar-wrap').load('/wp-content/themes/inthehills/ajax/calendar-events.php #calendar',{d:jQ(this).attr("data-date"),categories:cList},function(text,status,x) {
			calendar_init();
		});
		return false;
	});
	
	// Toggle event popup box
	jQ('#events-calendar td.event a.trigger').click(function() {

		var col_id = jQ(this).parents('td.event').index() + 1;
		
		/* If popup already visible, clicking again will hide it */
		if (jQ(this).siblings('div.popup').is(':hidden')) {
			jQ('#events-calendar .popup').fadeOut('fast');
			jQ(this).siblings('div.popup').addClass('col-' + col_id).fadeIn();
		} else {
			jQ(this).siblings('div.popup').fadeOut('fast');
		}
		
		return false;
	});

	// Close event popup box
	jQ('#events-calendar a.close').live('click', function() {
		jQ(this).parents('div.popup').fadeOut();
		return false;
	});
}

function limitedtext_updateDisplay(obj) {
	var maxLength=jQuery(obj).attr("data-limit");
	var dispField=jQuery(obj).attr("data-display");
	var curLength=obj.value.length;
	var charsLeft=maxLength-curLength;

	jQuery("#"+dispField).html(curLength+"/"+maxLength);
	jQuery("#"+dispField).attr("class","remain");
	if ((charsLeft<20)&&(charsLeft>=0)) jQuery("#"+dispField).addClass("warning");
	if (charsLeft<0) jQuery("#"+dispField).addClass("over");
}

function limitedtext_initialize(obj) {

	limitedtext_updateDisplay(obj);
	jQuery(obj).keyup(function() {
		limitedtext_updateDisplay(this);
	});
}


function multidate_initialize(obj) {

	var formName="";
	var fieldName=jQuery(obj).attr("data-name");
	var ps=jQuery(obj).parents();
	var theForm=null;

	for (var i=0;i<ps.length;i++) if (ps[i].tagName=="FORM") { theForm=ps[i]; break; }
	if (!theForm) return false;

	formName=jQuery(theForm).attr("name");

	var json="";
	var f=document.forms[formName];
	var curValue=f.elements[fieldName].value;
	json=jQ.toJSON({url:"multidate-list.php",target:"list",params:{v:curValue}});

	multidate_doAction(obj,fieldName,json);
}

function multidate_doAction(obj,fieldName,info) {

	if (COUNT>=20) return false;
	COUNT++;

	info=jQuery.parseJSON(info);
	if (info.error) {
		alert(info.error);
	}
	if (info.setValue) {
		var f=multidate_getForm(obj);
		var fieldName=jQuery(obj).attr("data-name");
		f[fieldName].value=info.setValue;
	}
	if ((info.target)&&(info.url)) {
		var params={};
		if (info.params) params=info.params;
		jQuery("#DATES_"+fieldName+"_"+info.target).load("/wp-content/themes/inthehills/js/widgets/"+info.url,params,function() {
			if (info.target=="list") multidate_initList(obj);
			else multidate_initControl(obj);

			var pl=jQuery(obj).find("."+info.target+" DIV.postLoad");
			if (pl.length) {
				var postLoad=jQuery(pl[0]).attr("data-info");
				if (postLoad!="") {
					multidate_doAction(obj,fieldName,postLoad);
					jQuery(pl[0]).attr("data-info","");
				}
			}
		});
	}
}

function multidate_initList(obj) {

	jQuery(obj).find("A.info").click(function() {
		var f=multidate_getForm(obj);
		var fieldName=jQuery(obj).attr("data-name");
		var curValue=f[fieldName].value;

		var json=jQ.toJSON({url:"multidate-control.php",target:"control",params:{v:curValue,mode:"update",index:jQuery(this).attr("data-index")}});
		multidate_doAction(obj,fieldName,json);
		return false;
	});

	jQuery(obj).find("INPUT.create").click(function() {
		var f=multidate_getForm(obj);
		var fieldName=jQuery(obj).attr("data-name");
		var curValue=f[fieldName].value;

		var json=jQ.toJSON({url:"multidate-control.php",target:"control",params:{v:curValue,mode:"create"}});
		multidate_doAction(obj,fieldName,json);
		return false;
	});

	jQuery(obj).find("INPUT.delete").click(function() {

		var cbs=jQuery(obj).find("INPUT.cb").filter(function(idx) { return (jQuery(this).attr("checked"))?1:0; });
		if (cbs.length>0) {
			if (window.confirm("Are you sure you want to delete the selected item(s)?")) {

				var fieldName=jQuery(obj).attr("data-name");
				var f=multidate_getForm(obj);
				var curValue=f[fieldName].value;

				var deleteArray=[];
				for (var i=0;i<cbs.length;i++) {
					deleteArray.push(jQuery(cbs[i]).attr("value"));
				}

				var json=jQ.toJSON({url:"multidate-list.php",target:"list",params:{
						v:curValue,
						mode:"delete",
						del:deleteArray
					}});

				multidate_doAction(obj,fieldName,json);

				return true;
			}
		}
		return false;
	});
}

function multidate_initControl(obj) {

	jQ(obj).find("INPUT.date").datepicker({
		changeMonth:true,
		changeYear:true,
		dateFormat:'dd-M-yy',
		autoSize:true,
		zIndex:100
	});

	jQ(obj).find("INPUT#DATE_from").datepicker("option","onSelect",function(fromText,inst) {

		var fromText=jQ(obj).find("INPUT#DATE_from").datepicker("getDate");
		var toText=jQ(obj).find("INPUT#DATE_to").datepicker("getDate");
		var fromDate=new Date(Date.parse(fromText));
		var toDate=new Date(Date.parse(toText));

		if ((toDate<fromDate)||(toText==null)) {
			jQ(obj).find("INPUT#DATE_to").datepicker("setDate",fromDate);
		}
		multidate_updateDayOfMonth(obj);
	});
	jQ(obj).find("INPUT#DATE_to").datepicker("option","onSelect",function(toText,inst) {

		var fromText=jQ(obj).find("INPUT#DATE_from").datepicker("getDate");
		var fromDate=new Date(Date.parse(fromText));
		var toText=jQ(obj).find("INPUT#DATE_to").datepicker("getDate");
		var toDate=new Date(Date.parse(toText));

		if ((toDate<fromDate)||(fromText==null)) {
			jQ(obj).find("INPUT#DATE_from").datepicker("setDate",toDate);
		}
		multidate_updateDayOfMonth(obj);
	});
	jQuery(obj).find("INPUT#DATE_multi_m").click(function() {
		if (jQuery(this).attr("checked")) {
			jQuery(obj).find("#DATE_toDate").show();
			jQuery(obj).find("#DATE_recur").show();
		}
		else {
			jQuery(obj).find("#DATE_toDate").hide();
			jQuery(obj).find("#DATE_recur").hide();
		}
	});
	jQuery(obj).find("INPUT#DATE_multi_s").click(function() {
		if (jQuery(this).attr("checked")) {
			jQuery(obj).find("#DATE_toDate").hide();
			jQuery(obj).find("#DATE_recur").hide();
		}
		else {
			jQuery(obj).find("#DATE_toDate").show();
			jQuery(obj).find("#DATE_recur").show();
		}
	});
	jQuery(obj).find("SELECT#DATE_recurUnit").change(function() {
		var s=jQuery(this).find("option:selected");
		var opt=jQuery(s[0]).attr("value");
		if (opt=="days") jQuery(obj).find("#DATE_recur_days").show();
		else jQuery(obj).find("#DATE_recur_days").hide();
		if (opt=="monthly") jQuery(obj).find("#DATE_recur_monthly").show();
		else jQuery(obj).find("#DATE_recur_monthly").hide();
	});
	jQuery(obj).find("SELECT#DATE_every").change(function() {
		var s=jQuery(this).find("option:selected");
		var opt=jQuery(s[0]).attr("value");
		if (opt=="9") {
			jQuery(obj).find("#DATE_every_day").hide();
			jQuery(obj).find("#DATE_every_day_specific").show();
		}
		else {
			jQuery(obj).find("#DATE_every_day").show();
			jQuery(obj).find("#DATE_every_day_specific").hide();
		}
	});
	jQuery(obj).find(".time_block input").change(function() {
		if (jQuery(this).attr("checked")) jQuery(obj).find(".time_info").show();
		else jQuery(obj).find(".time_info").hide();
	});
	jQuery(obj).find(".time select").change(function() {

		var f=multidate_getForm(obj);
		var mode="from";
		var fName=jQuery(this).attr("name");
		if (fName.match(/_to_/)) mode="to";

		var fromHour=f["TIME_from_hour"].options[f["TIME_from_hour"].selectedIndex].value;
		var fromMeridian=f["TIME_from_meridian"].options[f["TIME_from_meridian"].selectedIndex].value;
		if ((fromHour==12)&&(fromMeridian=="am")) fromHour="00";
		else if ((fromHour!=12)&&(fromMeridian=="pm")) fromHour=parseInt(fromHour,10)+12;
		var fromTime=fromHour+":"+f["TIME_from_min"].options[f["TIME_from_min"].selectedIndex].value;

		var toHour=f["TIME_to_hour"].options[f["TIME_to_hour"].selectedIndex].value;
		var toMeridian=f["TIME_to_meridian"].options[f["TIME_to_meridian"].selectedIndex].value;
		if ((toHour==12)&&(toMeridian=="am")) toHour="00";
		else if ((toHour!=12)&&(toMeridian=="pm")) toHour=parseInt(toHour,10)+12;
		var toTime=toHour+":"+f["TIME_to_min"].options[f["TIME_to_min"].selectedIndex].value;

		//alert(fromTime+" vs. "+toTime);
		if (fromTime>toTime) {
			if (mode=="from") { 
				// set "To" time to "from" time.
				f["TIME_to_hour"].selectedIndex=f["TIME_from_hour"].selectedIndex;
				f["TIME_to_min"].selectedIndex=f["TIME_from_min"].selectedIndex;
				f["TIME_to_meridian"].selectedIndex=f["TIME_from_meridian"].selectedIndex;
			}
			else {
				// set "From" time to "To" time.
				f["TIME_from_hour"].selectedIndex=f["TIME_to_hour"].selectedIndex;
				f["TIME_from_min"].selectedIndex=f["TIME_to_min"].selectedIndex;
				f["TIME_from_meridian"].selectedIndex=f["TIME_to_meridian"].selectedIndex;
			}
		}
	});

	jQuery(obj).find("INPUT.submit").click(function() {

		var fieldName=jQuery(obj).attr("data-name");
		var f=multidate_getForm(obj);
		var curValue=f[fieldName].value;

		var dayArray=[];
		var days=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
		for (var i=0;i<days.length;i++) {
			if (f["DATE_recur_days_"+days[i]].checked) dayArray.push(days[i]);
		}

		var multi=jQuery(obj).find("#DATE_multi_m").attr("checked");
		var json=jQ.toJSON({url:"multidate-list.php",target:"list",params:{
				v:curValue,
				DATE_multi:multi?1:0,
				DATE_from:f["DATE_from"].value,
				DATE_to:f["DATE_to"].value,
				DATE_recurUnit:f["DATE_recurUnit"].options[f["DATE_recurUnit"].selectedIndex].value,
				DATE_recur_days:dayArray,
				DATE_every:f["DATE_every"].options[f["DATE_every"].selectedIndex].value,
				DATE_every_day:f["DATE_every_day"].options[f["DATE_every_day"].selectedIndex].value,
				TIME_defined:f["TIME_defined"].checked?1:0,
				TIME_from_hour:f["TIME_from_hour"].options[f["TIME_from_hour"].selectedIndex].value,
				TIME_from_min:f["TIME_from_min"].options[f["TIME_from_min"].selectedIndex].value,
				TIME_from_meridian:f["TIME_from_meridian"].options[f["TIME_from_meridian"].selectedIndex].value,
				TIME_to_hour:f["TIME_to_hour"].options[f["TIME_to_hour"].selectedIndex].value,
				TIME_to_min:f["TIME_to_min"].options[f["TIME_to_min"].selectedIndex].value,
				TIME_to_meridian:f["TIME_to_meridian"].options[f["TIME_to_meridian"].selectedIndex].value,
				mode:f["DATE_mode"].value,
				index:f["DATE_index"].value
			}});

		multidate_doAction(obj,fieldName,json);

		return false;
	});

}

function multidate_updateDayOfMonth(obj) {
	var day=parseInt(jQuery(obj).find("INPUT#DATE_from").attr("value").substr(0,2),10);
	var suffix="th";

	if ((day==1)||(day==21)||(day==31)) suffix="st";
	else if ((day=="2")||(day==22)) suffix="nd";
	else if ((day=="3")||(day==23)) suffix="rd";

	jQuery("#DATE_every_day_specific").html(day+suffix+" of each month");
}

function multidate_getForm(obj) {
	var ps=jQuery(obj).parents();
	var theForm=null;
	for (var i=0;i<ps.length;i++) if (ps[i].tagName=="FORM") { theForm=ps[i]; break; }
	if (!theForm) return false;
	formName=jQuery(theForm).attr("name");

	return document.forms[formName].elements;
}

var rot13map = null;

function rot13init() {
	var map = new Array();
	var s   = "abcdefghijklmnopqrstuvwxyz";
	for (i=0; i<s.length; i++) map[s.charAt(i)]=s.charAt((i+13)%26);
	for (i=0; i<s.length; i++) map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();
	return map;
}

function rot13(a) {
	var s = "";
	if (!rot13map) rot13map=rot13init();
	for (i=0; i<a.length; i++) {
		var b = a.charAt(i);
		s += (b>='A' && b<='Z' || b>='a' && b<='z' ? rot13map[b] : b);
	}
	return s;
}


