
//Doc Ready functions go here
$(function() {
	
	//load extra CSS for firefox browser
	if (BrowserDetect.browser == 'Firefox' )
	{
		loadobject("/scripts/main_FF.css");
	}

	if (BrowserDetect.browser == 'Explorer' )
	{
		loadobject("/scripts/main_IE.css");
		
		//Add 17 px to each pane to accomodate for the scrollbar
		 $(".pane").each(function() {
		 	width = $(this).width() + 17;
		 	$(this).css("width",width+"px");
	    });
	}
	
	
	DV_MOVING = false;
	
	pirHeadings(""); //create all headings
	hasBasket();
	
	initGlobal();
	
	/*Enable Scale Nav Scroller*/
    $('#pane1').jScrollPane({scrollbarWidth:6, scrollbarMargin:10});
	
    /*Scale Nav Show/Hide Submenus*/
    $(".scale_nav").children("li").each(function() {
       if($(this).children("ul").length > 0){
       		$(this).addClass("open");
       }
    });
    
    $(".scale_nav").children("li").children("a").click(function()
    {
    	turnOnSecondLevelNavItem($(this).parent())
    });
    
     /*List Nav Show/Hide Submenus*/
    $(".list_nav").children("li").each(function() {
       if($(this).children("ul").length > 0){
       		$(this).addClass("open");
       }
    });
    
    $(".list_nav").children("li").children("a").click(function()
    {
    	turnOnSecondLevelListItem($(this).parent())
    });

});

function initGlobal(){
	
	var black_search_open_delay = 500;
	if(globalIsTouch){
		$('.black-li-search li').bind('touchstart', touch_black_li_search_li);
	}else{
		$(".black-li-search li").hover(
		    function()
		    {
		    	$(this).find("ul").css("visibility", "visible");
		    	clearTimeout($(this).find("ul").data("tocloseid"));
		    },
		    function()
		    {
		    	var menuClose = $(this).find("ul");
		    	var timer = setTimeout(function()
	            {
	               menuClose.css("visibility", "hidden");
	
	            }, black_search_open_delay);
		    	menuClose.data("tocloseid", timer);
		    }
	    );
	}
    
	$(".black-searchbox").focus(function () {
		if($(this).val() == "Search"){
			$(this).val('');
		}
	});
	$(".black-searchbox").blur(function () {
		if($(this).val() == ""){
			$(this).val('Search');
		}
	});

	//youtube image replacement on link
	$('a.youtube-large').each(function(){
		ytHref = $(this).attr('href');
		imgUrl = $.jYoutube(ytHref, 'large');
		$(this).html('<img class="youtube-play" src="'+imgUrl+'" />');
	});
	
	
	$(window).resize(function() {
		checkTopFavHeight();
	});
	
	

	  
}

function initLoadMore(target){
	//youtube image replacement on link
	target.find('a.youtube-large').each(function(){
		ytHref = $(this).attr('href');
		imgUrl = $.jYoutube(ytHref, 'large');
		if($(this).text() == "Youtube Player"){
			$(this).html('<img class="youtube-play" src="'+imgUrl+'" />');
		}
	});
}

function touch_black_li_search_li(){
	if($(this).find("ul").css("visibility") == "hidden"){
		$(this).find("ul").css("visibility", "visible");
		clearTimeout($(this).find("ul").data("tocloseid"));
	}else{
		$(this).find("ul").css("visibility", "hidden");
	}
}


function jumpTo(p){
	if (BrowserDetect.browser == 'Explorer'){
		$("#wrapper").scrollTo( $('#pane-wrapper-' + p), 800 );
	}else{
		if(typeof(myScrollH) != "undefined"){ 
			myScrollH.scrollToElement('#pane-wrapper-' + p, '350');
		}
	}
}
	
	
function doHash(hash)
{
	if(typeof(iscrollModel) != "undefined"){ 
	    // do stuff that loads page content based on hash variable
	    iscrollModel.init(hash); 
	}
}

$(document).ready(function() {
	
	if(typeof(scrollPage) == "undefined"){ 
		scrollPage = false;
	}
	
	if(typeof($.history) != "undefined" && (scrollPage != true || BrowserDetect.browser == 'Explorer')){ 
		
		//added to process the hash after the panes have been inititated
		$.history.init(doHash,{ unescape: "~=/?" });
	}
	
	//Waldo: I disabled this as the ajax calls was being processed twice on the awards archive etc. when clicking on the main nav.
//	$('a[rel*=iscrollHistory]').click(function() { 
//		
//		//we needed to still process the hash even if it didn't change, only if the navigation was clicked.
//		var vars = $(this).attr("href").split(/#/);
//		vars.shift();
//		var tmp_hash = vars.join("#");
//		var is_ok=tmp_hash.indexOf('pane='+iscrollModel.getCurrentPane());
//		if ((is_ok != -1)){ 
////			doHash(tmp_hash);
//		}
//	});
});


 var iscrollModel = {
 	actions: [],
    init: function(hash) {
    	this.initActions(hash); 
    },
    getCurrentPane: function() {
   		return this.actions["pane"]
    },
    initActions: function(hash) {
    	
    	//Google Analytics!!!
    	page_location = window.location.pathname+''+window.location.hash;
    	_gaq.push(['_trackPageview', page_location]);
    	
    	var tmp_action= new Array()
    	var vars = hash.split(/~/);
    	
    	$.each( vars, function(i, n){
    		var tmp = n.split(/=/);
    		key = tmp.shift();
    		value = tmp.join("=");
//        		alert("key: "+key+" - value: "+value);
		 	tmp_action[key] = value
		});
		
		this.actions = tmp_action;
		this.render();
    },
    render: function() {
    	
    	if(typeof(this.actions["pane"]) != "undefined"){ 
//        		console.log("jumpTo('"+this.actions["pane"]+"')");
    		jumpTo(this.actions["pane"]);
    		
    		if(typeof(this.actions["url"]) != "undefined"){ 
				var target = $('#pane-wrapper-'+this.actions["pane"]).find('.sub-pane').attr("id");
				var resetPos = ''
				
				if (BrowserDetect.browser == 'Explorer'){
					
					AjaxCall(this.actions["url"], target,  function(){}, 1);
					
				}else{
				
					for(var i = 0; i < $(".sub-pane").length; i++){
						if($(myScrollPanes[i].wrapper).attr("id") == 'pane-wrapper-'+this.actions["pane"]){
							resetPos = i
						}
					}
					
					AjaxCall(this.actions["url"], target,  function(){
																if(resetPos != ''){
																	myScrollPanes[resetPos].scrollTo(0, 0);
																}
																domChanged();
															}, 1);
				}										
        	}
    		    		
    		if(typeof(this.actions["scroll"]) != "undefined"){ 
    			for(var i = 0; i < $(".sub-pane").length; i++){
					if($(myScrollPanes[i].wrapper).attr("id") == 'pane-wrapper-'+this.actions["pane"]){
						scrollPaneIndex = i
					}
				}
    			
    			myScrollPanes[scrollPaneIndex].scrollToElement("#"+this.actions["scroll"],350);
    		}    		
    	}  	    	
  	
    	if(typeof(this.actions["ol"]) != "undefined"){ 
    		jQuery.facebox({ ajax: this.actions["ol"],  loadingImage : '/images/loading.gif' });
    	}else if(typeof(this.actions["olb"]) != "undefined"){ 
    		FACEBOXDONOTISCROLL = 1;
    		jQuery.facebox({ ajax: this.actions["olb"], faceboxBackgroundStyle: "faceboxBlack",  loadingImage : '/images/loading_blk.gif' });
    	}else if(typeof(this.actions["yt"]) != "undefined"){
    		FACEBOXDONOTISCROLL = 1;
    		jQuery.facebox({ youtube: this.actions["yt"], faceboxBackgroundStyle: "faceboxBlack",  loadingImage : '/images/loading_blk.gif' });
    	}else if ($("#facebox").exists()){ 
    		if (!$("#facebox").is(":hidden")){
        		jQuery(document).trigger('close.facebox');
    		}
    	}
    	
    	//if a width is passed through change the faebox width to the value supplied
    	if(typeof(this.actions["olw"]) != "undefined"){ 
    		$("#faceboxBody").css({width: this.actions["olw"]+"px"});
    	}

    }
}
 
function closeFacebox(){
	 jQuery(document).trigger('close.facebox');	 
}


function domChanged(){
	
	if(typeof(myScrollPanes) != "undefined"){ 
		for(var i = 0; i < myScrollPanes.length; i ++){
			var divPaneNo = i+1;
			myScrollPanes[i].refresh();
		}
	}
}

function loadHash(hash)
{
	if(typeof($.history) != "undefined"){ 
   		$.history.load(hash);
	}
}

function setSideHeight(){
	
//	alert($(document).height(). " -> "+window.innerHeight)
	
//	var headerH = document.getElementById('header').offsetHeight;
	var headerH = $('#header').outerHeight();
//	var wrapperH = window.innerHeight - headerH - 55;
	var wrapperH = $(window).height() - headerH - 55;

	//document.getElementById('menu-left').style.height = wrapperH - 78 + 'px';
	$('#menu-left').css("height", wrapperH - 78 + 'px');

}

function turnOnSecondLevelNavItem(item){
	if(item.children("ul").length > 0){
		item.children("ul").toggle();
	  	item.toggleClass("close");
	   	$('#pane1').jScrollPane({scrollbarWidth:6, scrollbarMargin:10});
	}else{
		item.addClass("on");
		item.children('a').addClass("on");
	}
}

function turnOnSecondLevelListItem(item){
	if(item.children("ul").length > 0){
		item.children("ul").toggle();
	  	item.toggleClass("close");
	}else{
		item.addClass("on");
		item.children('a').addClass("on");
	}
}



function pirHeadings(target){
		
	$.pir.options.php="/images/pir/pir.php";
	
	if(target != ""){
		$(target).find("h1").pir({font: "DIN-Medium.otf", size: "48", color: "#a6a6a6"});
		$(target).find("h2").pir({font: "DIN-Medium.otf", size: "16", color: "#a6a6a6"});
		$(target).find("h3").pir({font: "DIN-Medium.otf", size: "28", color: "#a6a6a6"});
		$(target).find("h4").pir({font: "DIN-Medium.otf", size: "14", color: "#FFFFFF"});
		$(target).find("h5").pir({font: "DIN-Medium.otf", size: "20", color: "#0088cc"});
		$(target).find("h6").pir({font: "DIN-Medium.otf", size: "16", color: "#676765"});
	}else{
		$("h1").pir({font: "DIN-Medium.otf", size: "48", color: "#a6a6a6"});
		$("h2").pir({font: "DIN-Medium.otf", size: "16", color: "#a6a6a6"});
		$("h3").pir({font: "DIN-Medium.otf", size: "34", color: "#a6a6a6"});
		$("h4").pir({font: "DIN-Medium.otf", size: "14", color: "#FFFFFF"});
		$("h5").pir({font: "DIN-Medium.otf", size: "20", color: "#0088cc"});
		$("h6").pir({font: "DIN-Medium.otf", size: "16", color: "#676765"});
	}

	$(target+".nv-mn").pir({font: "DIN-Medium.otf", size: "14", color: "#666666"});
//	$(target+".nv_on").pir({font: "DIN-Medium.otf", size: "10", color: "#cc0001"});
//	$(target+".nv-ft").pir({font: "DIN-Medium.otf", size: "10", color: "#666666"});
	
//	$(target+".nv-left").pir({font: "DIN-Medium.otf", size: "9", color: "#666666", bgcolor: "transparent"});
//	$(target+".nv-left-heading").pir({font: "DIN-Medium.otf", size: "9", color: "#666666", bgcolor: "transparent"});
	
//	$(target+".box_title").pir({font: "DIN-Regular.otf", size: "14", color: "#FFFFFF"});
	
	//all themed headings
//	$(target+"._title").pir({font: "DIN-Regular.otf", size: "14", color: "#666666"});
//	$(target+".blue_title").pir({font: "DIN-Regular.otf", size: "14", color: "#006699"}); //blue_theme
//	$(target+".green_title").pir({font: "DIN-Regular.otf", size: "14", color: "#5e9900"}); //green_theme
//	$(target+".maroon_title").pir({font: "DIN-Regular.otf", size: "14", color: "#7c0000"}); //maroon_theme
//	$(target+".orange_title").pir({font: "DIN-Regular.otf", size: "14", color: "#ff9900"}); //orange_theme
//	$(target+".purple_title").pir({font: "DIN-Regular.otf", size: "14", color: "#663399"}); //purple_theme
//	$(target+".red_title").pir({font: "DIN-Regular.otf", size: "14", color: "#cc0000"}); //red_theme
//	$(target+".turquoise_title").pir({font: "DIN-Regular.otf", size: "14", color: "#009999"}); //turquoise_theme
}

function AjaxCall(url, target, callback, pane_load ){
	if(url != "" && target != ""){
		$.get(url, { ajax: "true", pane_load: pane_load},
		  function(data){
		  	$("#"+target).html(data);
		  	
		  	if (typeof(callback) == 'function') {
				callback();
			}
			
			pirHeadings("#"+target); //create all headings
			initGlobal();
		});
	}
}

function closeAllTopBoxes(){
	$('.top_overlay').html('');
}

function getTopBasket(){
	closeAllTopBoxes();
	$('#ajaxBasketTop').html('<div style=\'border: 1px Solid #000; padding: 5px; background: #fff\'><img src=\'/images/loading.gif\' width=\'10\' height=\'10\' alt=\'\' /> Loading...</div>'); 
	AjaxCall('/_ajax/store/?action=sideBasket&ref=/store/&sideBasketType=landing', 'ajaxBasketTop');
}

function getTopFavs(){
	closeAllTopBoxes();
	$('#ajaxFavTop').html('<div style=\'border: 1px Solid #000; padding: 5px; background: #fff\'><img src=\'/images/loading.gif\' width=\'10\' height=\'10\' alt=\'\' /> Loading...</div>'); 
	AjaxCall("/_ajax/favorites/?action=topFavs", "ajaxFavTop", function(){checkTopFavHeight();});
//																
															
}

function addFav(url){
	if(url != ""){
		$.get(url, { ajax: "true"},
		  function(data){
		  	alert(data);
		});
	}else{
		alert("Could not add to your favorites. No Action specified.")
	}
}


function hasBasket(){
	$.get('/_ajax/store/?action=hasBasket', { ajax: "true"},
	  function(data){
	  	if(data == "1"){
	  		$('#basketIcon').show()
	  	}
	});
}


function getTopMailingList(){
	closeAllTopBoxes();
	$('#ajaxJoinMailingList').html('<div style=\'border: 1px Solid #000; padding: 5px; background: #fff\'><img src=\'/images/loading.gif\' width=\'10\' height=\'10\' alt=\'\' /> Loading...</div>'); 
	AjaxCall('/_ajax/constituent/?action=topMailingList', 'ajaxJoinMailingList');
}


function submitForm(theform, theaction){
	theform.action = theaction;
	theform.submit();
}

function replaceAll(txt, replace, with_this) {
	//	var origString = txt;
//	var inChar = replace;
//	var outChar = with_this;
//	
//	var newString = origString.split(inChar);
//	newString = newString.join(outChar);
//	
//	return newString
	
  return txt.replace(new RegExp(replace, 'g'),with_this);
}

function goTopOfPage(){
	$('html, body').animate({scrollTop:0}, 'slow');
}


function toggleTable(el,st) {
	if(st == 1){
		$("#"+el).show();
	}else{
		$("#"+el).hide();
	}	
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
		
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}


//function that can be used to determine if an element exits
//usage: 
//if ($(selector).exists()) {
//    // Do something
//}
jQuery.fn.exists = function(){
	return jQuery(this).length>0;
}

//to detect if an elemnet has focus
jQuery.extend(jQuery.expr[':'], {
    focus: function(element) { 
        return element == document.activeElement; 
    }
});




/**
* radioStateClick
*/
//Handles on/off states in a radio button style -> Only one out of a list of selectors will be on at a time
$.fn.radioStateClick = function ()
{
    var allbuttons = $(this);
    $(this).click(function()
    {
       $(allbuttons).offImage();
       $(this).onImage();
       
       state = 1;
       if($(this).hasClass('viewtwo')){
       		state = 2;
       }else if($(this).hasClass('viewthree')){
       		state = 3;
       }
       
        $.get("/", { ajax: "true", radioStateClick: state},
		  function(data){
		  	//do nothing
		});
       
    });
    return $(this);
};




/*Handlers for on off state images*/

//Replaces an off image with an on image e.g. button_off.gif -> button_on.gif
$.fn.onImage = function ()
{
    $(this).each(function ()
    {
        $(this).attr('src', $(this).attr('src').replace('_off.', '_on.'));
        return $(this);
    });
}

//Replaces an on image with an off image e.g. button_on.gif -> button_off.gif
$.fn.offImage = function ()
{
    $(this).each(function ()
    {
        $(this).attr('src', $(this).attr('src').replace('_on.', '_off.'));
        return $(this);
    });
    
}



//Handles on/off states for mouse hover instead of click as above
$.fn.radioStateHover = function ()
{
    var allbuttons = $(this);
    
    $(this).each(function()
    {
        $(this).hover(function()
        {
           $(this).onImage();
        },
        function()
        {
            $(this).offImage();
        });
    })
    return $(this);
}


$.fn.increaseFontsize = function(increment, max, speed, easing, callback) {
	
	var currentFontSize = this.css('font-size');
	var currentFontSizeNum = parseFloat(currentFontSize, 10);
   	var size = currentFontSizeNum+increment;
	
	if(size > max){
		size = max;
	}
	
	return this.animate({fontSize: size+"px"}, speed, easing, callback);
};

$.fn.decreaseFontsize = function(decrement, min, speed, easing, callback) {
	var currentFontSize = this.css('font-size');
	var currentFontSizeNum = parseFloat(currentFontSize, 10);
   	var size = currentFontSizeNum-decrement;
	
	if(size < min){
		size = min;
	}
	
	return this.animate({fontSize: size+"px"}, speed, easing, callback);
};

$.fn.greyHoverState = function ()
{
    var allbuttons = $(this);
    
    $(this).each(function()
    {
    	var img = $(this).children('div').children('img:first');
    	
    	Pixastic.process(document.getElementById(img.attr("id")), "desaturate", {average : false});
    	
        $(this).hover(function()
        {
           Pixastic.revert(document.getElementById(img.attr("id")));
        },
        function()
        {
			Pixastic.process(document.getElementById(img.attr("id")), "desaturate", {average : false});
        });
    })
    return $(this);
}


function sleep(numberMillis)
{
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true)
	{
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	}
} 

function deleteForm(theform, theaction, allShow){
	var item_selected = 0;

	if(theform.elements[allShow + "_id[]"].checked == true){
		item_selected = 1;
	}
	
	for(x = 0;x < theform.elements[allShow + "_id[]"].length; x++){
		if(theform.elements[allShow + "_id[]"][x].checked == true){
			item_selected = 1;
			break;	
		};
	}
	
	if(item_selected == 1){
		if(confirm("Do you really want to delete selected entries?")){
			theform.action = theaction;
			theform.submit();
		}
	}else{
		alert("Please select entries you want to delete.");	
	}
}

function editFormEntry(theform, theaction, allShow, actType){
	edit_count = 0;
	
	if(theform.elements[allShow+"_id[]"].checked == true){
		entry_id = theform.elements[allShow+"_id[]"].value;
		edit_count = 1;
	}
	
	for(x = 0;x < theform.elements[allShow+"_id[]"].length; x++){
		if(theform.elements[allShow+"_id[]"][x].checked == true){
			entry_id = theform.elements[allShow+"_id[]"][x].value;
			edit_count ++;
			if(edit_count > 1){
				break;
			}
		};
	}
	
	if(edit_count == 0){
		alert("Please select an entry you want to "+actType+".");
	}else if(edit_count > 1){
		alert("Please only select a single entry you want to "+actType+".");
	}else{
		window.location = theaction + entry_id;
	}
}

function loadobject(file){
	if (file.indexOf(".js")!=-1){ //If object is a js file
		fileref=document.createElement('script')
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", file);
	}
	else if (file.indexOf(".css")!=-1){ //If object is a css file
		fileref=document.createElement("link")
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", file);
	}
	document.getElementsByTagName("head").item(0).appendChild(fileref)
}
