/*
Javascript code supporting ajax functionalities.
*/

var NotesCookie = false;
var PrintCartCookie = false;
var LinkCartCookie  = false;
var dldInProgress = false;
var basepath = '/';
var notesUrl = "";
var printUrl = "";
var LinksUrl = "";
var mailerUrl = "";
var feedbackUrl = "";
var downloadsUrl = "";
var exitUrl = "";
var options = false;

function establishPgId()
{
	
	return getPageFromLink('ul#tools li a.first');
}		


function isInCart(){
		var value =  PrintCartCookie;
		return (value != null && (','+value+',').indexOf(','+establishPgId()+',')>-1);
}
	
function setCartPageStatus(){
		if (isInCart()){
			$('a#printbasket').parents("li:first").find("a:first").hide();
			$('a#printbasket').parents("li:first").find("em:first").hide();
			$('a#printbasket').next().next().addClass("second");
		}
}

function getPageFromLink(link){			
		var pg = $(link).attr('href');
		var rg = new RegExp("pg\\d+");
		var res = rg.exec(pg);
		return res;
}
function displayPopup(){
	$('body').append('<div id="dialog" class="jqmWindow"><a class="close" style="float:right;" href="#"><span>Close</span></a><div class="content"></div><div id="splash"><h2>Processing...</h2><img src="'+basepath+'images/loading.gif" /></div></div>');
	$('#dialog').jqm({onShow: showEvent, modal: true}).jqmShow();
	$('div.jqmOverlay').click(function(){ClosePopup();});
	$('.close').click(function(){ClosePopup();});
}
function showEvent(hash){
		SetSplashStatus(true);
		hash.w.show();
		$.get(options['url'],options['params'],function (data){
				loadEvent(data);
			}
	);
}
function loadEvent(data){
	$('#dialog > div.content').html(data);
	SetSplashStatus(false);
	if (options['CancelAction']){
			$(options['CancelAction']).click(function(){
				ClosePopup();
				return false;
			});
			$(options['CancelAction']).show();
	}		
	if (options['DoAction']) {
		$(options['DoAction']).click(submitEvent);
	}
	
	if (options['loadCallback']) {
		options['loadCallback']();
	}
}

function submitEvent(data){
	  SetSplashStatus(true);
	  var fields = $('#dialog > div.content').find(":input");
	  var inputs = getAjaxFormFields(fields);
	  $.get(options['url'],inputs,function (data){
	  		if (options['submitCallback'] != null)
	  			options['submitCallback']();
			else
				loadEvent(data);
	  	});
		return false;
}
function ClosePopup(){
	$('#dialog').jqmHide();
	$('#dialog').remove();
}

function getAjaxFormFields(fields){
	var inputs = new Object();
	inputs['ajax']=1;
	for (i=0;i<fields.length;i++){
	  	if (fields[i].name != '') {
			if ((fields[i].type == 'radio' || fields[i].type == 'checkbox')){
				if (fields[i].checked) inputs[fields[i].name]= fields[i].value;
			}
			else
				inputs[fields[i].name]= fields[i].value;
		}
	}
	return inputs;
}

function SetSplashStatus(visible){
	if (visible){
		$('#splash').show();
		$('#dialog > div.content').hide();
	}
	else{
		$('#splash').hide();
		$('#dialog > div.content').show();
	}
}


$(document).ready(function() {
/*Code for report tools begins*/
			basepath = $('a#logo').attr('href').replace('index.html','');
			//define urls
			printUrl = basepath+'scripts/print.php';
			mailerUrl = basepath+'scripts/email.php';
			exitUrl = basepath+'scripts/exit.php';
			feedbackUrl = basepath+'scripts/feedback.php';
			
			$('#print_all').click(function (){
				$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
			});
		   $('#delete_all').click(function (){
				$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
			});
		   $('#email_all').click(function (){
				$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
			});
		    
			$('a.printButton').click(function() {
				window.print();
		  });
		  
		  PrintCartCookie = $.ajax({type: 'GET',url: printUrl,async: false,data: {ajax: 1, ajxcmd: 'getcookie'},dataType: 'text'}).responseText;
		  
		  
		   
		  $('ul#tools li a.first').click(function(){
				options = {url: mailerUrl,params: {ajax:1,pg:getPageFromLink('ul#tools li a.first')},CancelAction: '.CancelSend',DoAction: '.ActionSend'};
				displayPopup();
				return false;		
		   });  	
		
		  $('li.feedback a').click(function(){
				options = {url: feedbackUrl,params: {ajax:1},CancelAction: '.CancelSend',DoAction: '.ActionSend'};
				displayPopup();
				return false;		
		   });  	
		
		
		   $('a.external').click(function (){
						var surl = (this.href.indexOf('url=')>0) ? this.href.substring(this.href.indexOf('url=')+4) : this.href;
						options = {url: exitUrl,params: {url:surl},CancelAction: '.CancelExit'};
						displayPopup();
						return false;
			 });
		   
		   
		   // Cookie js finds if persistent cookies are enabled
			setCartPageStatus();
/*Code for report tools ends*/
var theHost=jQuery.url.attr("host");

// Even nav
function evenNav(items,width,ems){
    var theWidth=0;
    items=items*2;
    $('#top_nav li').each(function(){
       theWidth=theWidth+$(this).width();
    });
    var spacing=width-theWidth;
    spacing=spacing/items;
    spacing=Math.floor(spacing);
    $('#top_nav li').css("padding-left",spacing).css("padding-right",spacing)

};
evenNav("6","790","");

// end even nav


/*
//ADDISON DEFAULT ACCORDION
if ($('#accordion').length != 0) {
	$('#accordion h2').next("div").each(function(){
				if ($('body').css('minWidth')==undefined){
		$(this).attr("rel",$(this).height()+30);
				} else {
					$(this).attr("rel",$(this).height());
				};
	});
	// Open first one
	//$('#accordion h3:first').addClass("ui-state-active").next('div');
	$('#accordion h2')//.not('#accordion h3:first')
		.each(function(){
			$(this).next("div").css("height","0");
			$(this).next("div").addClass("closedAccordion");
	});
	$('#accordion h2').live("click",function(){
		accordion($(this),"#accordion h2","",$('#accordion h2').index(this));
		activeAccSubSection = false;
		return false;
	});	
};
// END ADDISON DEFAULT ACCORDION

// variable for accordion section
activeAccSubSection = false;
// variable for accordiion subsection and anchor
activeAccSubSectionAnchor = false;
	
	
// Back button rememberance
$(window).unload(function() {
	// detect accordion
	_accordion='false';
	Pos=0;
	index=0;
	if ($('#accordion').length>0){
		if ($('h3').hasClass('current')){
        	Pos=($('#accordion h2').index($('#accordion h2.current')));
            _accordion='true';
        };
	} else {
    	Pos=$(window).scrollTop();
    };
	// end detect accordion

	if (!$.cookie('COOKIE_INDEX')){
		var options = { path: '/'};
		var COOKIE_INDEX=1;
		$.cookie('COOKIE_INDEX', COOKIE_INDEX, options);
	} else {
		var options = { path: '/'};
		var COOKIE_INDEX=parseInt($.cookie('COOKIE_INDEX'))+1;
		$.cookie('COOKIE_INDEX', COOKIE_INDEX, options);
	};
	var pageIndex=parseInt($.cookie('COOKIE_INDEX'));
	var options = { path: '/'};
	var pageData =new Array(jQuery.url.attr("path"),_accordion,Pos);
	$.cookie('PAGE_URL'+pageIndex,pageData,options);
});
 // End back button rememberance



// if back button rememberance go to that point in page
if (location.hash){	
	// remove the # (the hash can container either a number or text)
	var activeAcc=(location.hash).replace('#','');
	// test to find subsection anchor
	activeAccSubSectionTest = activeAcc.indexOf('=');
	activeAccSubSection = false;	
	// if test is true
	if(activeAccSubSectionTest != '-1'){
		// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
		activeAccSubSection = activeAcc.split('=', [2]);
		// place sub section accordion varibale within activeAcc
		activeAcc = activeAccSubSection[0];
	} else {
		// else test if activeAcc is either a number or text
		if(/^\d*$/.test(activeAcc)){
			// if a number turn into a interger
			activeAcc=parseInt(activeAcc);
		} else {
			// else activeAcc is a text anchor
			activeAccSubSectionAnchor = activeAcc;
		}
	}
	activeAcc=parseInt(activeAcc);
	if(activeAccSubSectionAnchor){
		// them scroll to anchor
		$(window).scrollTo($('#'+activeAccSubSectionAnchor), 800 );
	} else {
		accordion($('#accordion h2').eq(activeAcc),"#accordion h2","true",activeAcc);	
	}
} else if ($.cookie('COOKIE_INDEX')){
	var currentPage=parseInt($.cookie('COOKIE_INDEX'))-1;
	currentPage=$.cookie('PAGE_URL'+currentPage);
	if (!currentPage==""){
		currentPage=currentPage.split(',');
		if (currentPage[0]==jQuery.url.attr("path")){
			$('*').stop(true,true);
			// if was accordion open it and got to position		
			if (currentPage[1]=="true"){
				accordion($('#accordion h2').eq(currentPage[2]),"#accordion h2","true",currentPage[2]);
				var accPos=$('h2.ui-accordion-header').eq(currentPage[2]).offset();
				$(window).scrollTop(accPos.top);
			 } else {
				// no hash then false
				var t=setTimeout(firstItem,1000);				 	 
			 }
			 // end if was accordion open it and got to position
		} else {
			var t=setTimeout(firstItem,1000);
		}
	} else {
		// no hash then false
		var t=setTimeout(firstItem,1000);	
	}
} else {
	// no hash then false
	var t=setTimeout(firstItem,1000);
};
	
	

// Accordion function with options - pass in the object (Header) thats been clicked		
function accordion(element,header,type,index){
		$('#accordion h2').each(function(){
			if($(this).hasClass('current')){
				$(this).removeClass("current");
			}
		});
	var height=element.next("div").attr('rel');
	if (element.hasClass("ui-state-active")){
		
		element.next("div").animate({
			height: "0"		
		}, 500).addClass("closedAccordion").prev(header).removeClass("ui-state-active").removeClass('current');
	} else {
		element.next("div").animate({
			height: height
		}, 500,function(){
			if(type != 'false'){
				if(!activeAccSubSection){
					$(window).scrollTo( $(header).eq(index), 800);
				} else {
					$(window).scrollTo( $('#'+activeAccSubSection[1]), 800);
				}
			}
		}).removeClass("closedAccordion").prev(header).addClass("ui-state-active").addClass('current');
	};
};	
function firstItem(){
	accordion($('#accordion h2:first'),'#accordion h2','false',0);
};
// End Accordion function with options - pass in the object (Header) thats been clicked


$('#contentArea a').click(function(){
	theLink = false;
	theLink = $(this).attr('href');
	theLinkTest = theLink.indexOf('#');
	if(theLinkTest != '-1'){
		var splitHash = $(this).attr('href').split('#');
			// remove #
			var activeAcc=splitHash[1];	
			// test to find subsection anchor
			activeAccSubSectionTest = activeAcc.indexOf('=');
			activeAccSubSection = false;
			// if test is true
			if(activeAccSubSectionTest != '-1'){
				// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
				activeAccSubSection = activeAcc.split('=', [2]);
				// place sub section accordion varibale within activeAcc
				activeAcc = activeAccSubSection[0];
			}
			// test if activeAcc is either a number or text
			if(/^\d*$/.test(activeAcc)){
				activeAcc=parseInt(activeAcc);
				$(window).scrollTo($('body'), 800, function(){
						// if a sub section with a anchor exist then scroll that anchor after accordion has opened correct section
						isclosed = $('#accordion h2').eq(activeAcc).next().hasClass('closedAccordion');
						if(activeAccSubSection){
							if(isclosed){
								accordion($('#accordion h2').eq(activeAcc),"#accordion h2","true",activeAccSubSection[1]);
							} else {
								$(window).scrollTo( $('#'+activeAccSubSection[1]), 800);
							}
						} else {
							// if no anchor within a sub section exist then scroll to open accordion
							if(isclosed){
								accordion($('#accordion h2').eq(activeAcc),"#accordion h2","true",activeAcc);
							} else {
								$(window).scrollTo( $('#accordion h2').eq(activeAcc), 800);
							}
						}
				});
			} else {
				// if #hash change was for a anchor within already open accordion then just go the right anchor without any accodion effect 
				$(window).scrollTo($('#'+activeAcc), 800 );
			}
	}
});





*/


















/*



//ADDISON DEFAULT ACCORDION / you require a containing div with the id 'accordion' and give it a class of clearfix
if ($('#accordion').length != 0) {
	$('#accordion h2').next("div").each(function(){
    	if ($('body').css('minWidth')==undefined){
			$(this).attr("title",$(this).height()+30);
		} else {
			$(this).attr("title",$(this).height());
		}
	});
    // Open first one
    $('#accordion h2:first').addClass("open");
    $('#accordion h2').not('#accordion h2:first').each(function(){
		$(this).next("div").css("height","0");
    });
    $('#accordion h2').live("click",function(){
    	accordion($(this),"h2");
    });
};


// Accordion function with options - element = 'element clicked', header = 'h2 or h3 etc',type(optional)='for scrolling to opened item', index(optional)='again for scrolling''
function accordion(element,header,type,index){
	var height=element.next("div").attr('title');
    // For scrollto		
	if (type=="open"){
		if (!element.hasClass("open")){
        	element.next("div").animate({
            height: height
		}, 500, function(){$(window).scrollTo( $(header).eq(index), 800 )}).prev(header).addClass("open");
    	} else {
    		$(window).scrollTo( $(header).eq(index), 800 ).prev(header).addClass("open");
	    };
	// End for scrollto
	} else {
		if (element.hasClass("open")){
			element.next("div").animate({
            	height: "0"
        	}, 500).prev(header).removeClass("open");
		} else {
			openDivs = $('#accordion h2');
			if(openDivs.hasClass('open')){
				$(openDivs).next("div").animate({
					height: '0'
				}, 800).prev(header).removeClass("open");
			}
			element.next("div").animate({
            	height: height
            }, 500).prev(header).addClass("open");
         };
	};
};
// End Accordion function with options - pass in the object (Header) thats been clicked
// END ACCORDION

*/




/*
//ADDISON DEFAULT ACCORDION / you require a containing div with the id 'accordion' and give it a class of clearfix
if ($('#accordion').length != 0) {
	
	collapseTest = $('#accordion');
	
	collapse = false;
	
	if(collapseTest.hasClass('collapse')){
		collapse = true;
	}
		
	$('#accordion h2').next("div").each(function(){
    	if ($('body').css('minWidth')==undefined){
			$(this).attr("title",$(this).height()+30);
		} else {
			$(this).attr("title",$(this).height());
		}
	});
    // Open first one
    $('#accordion h2:first').addClass("open");
    $('#accordion h2').not('#accordion h2:first').each(function(){
		$(this).next("div").css("height","0");
    });
    $('#accordion h2').live("click",function(){
											 
		
											 
											 
    	accordion($(this),"h2", null, null, collapse);
    });
};


// Accordion function with options - element = 'element clicked', header = 'h2 or h3 etc',type(optional)='for scrolling to opened item', index(optional)='again for scrolling''
function accordion(element,header,type,index, collapse){
	var height=element.next("div").attr('title');
    // For scrollto		
	if (type=="open"){
		if (!element.hasClass("open")){
        	element.next("div").animate({
            height: height
		}, 500, function(){$(window).scrollTo( $(header).eq(index), 800 )}).prev(header).addClass("open");
    	} else {
    		$(window).scrollTo( $(header).eq(index), 800 ).prev(header).addClass("open");
	    };
	// End for scrollto
	} else {
		if (element.hasClass("open")){
			element.next("div").animate({
            	height: "0"
        	}, 500).prev(header).removeClass("open");
		} else {
			
			
			if(collapse == true){
				openDivs = $('#accordion h2');
				if(openDivs.hasClass('open')){
					$(openDivs).next("div").animate({
						height: '0'
					}, 800).prev(header).removeClass("open");
				}
			}
			
			
			
			element.next("div").animate({
            	height: height
            }, 500).prev(header).addClass("open");
         };
	};
};
// End Accordion function with options - pass in the object (Header) thats been clicked
// END ACCORDION


*/


// Accordion
// variable for accordion section
activeAccSubSection = false;
// variable for accordiion subsection and anchor
activeAccSubSectionAnchor = false;

if (location.hash){	
	// remove the # (the has hash can container either a number or text)
	var activeAcc=(location.hash).replace('#','');
	// test to find subsection anchor
	activeAccSubSectionTest = activeAcc.indexOf('=');
	activeAccSubSection = false;
	// if test is true
	if(activeAccSubSectionTest != '-1'){
		// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
		activeAccSubSection = activeAcc.split('=', [2]);
		// place sub section accordion varibale within activeAcc
		activeAcc = activeAccSubSection[0];
	} else {
		// else test if activeAcc is either a number or text
		if(/^\d*$/.test(activeAcc)){
			// if a number turn into a interger
			activeAcc=parseInt(activeAcc);
		} else {
			// else activeAcc is a text anchor
			activeAccSubSectionAnchor = activeAcc;
		}
	}
	activeAcc=parseInt(activeAcc);
	
	
} else {
	// no hash then false
	var activeAcc=0;
	activeAcc=parseInt(activeAcc);
};






//	only a anchor exisit (no accordion needed)
if(activeAccSubSectionAnchor){
	// them scroll to anchor
	$(window).scrollTo($('#'+activeAccSubSectionAnchor), 800 );
} else {
	
	if(activeAcc == 0){
		$("#accordion").accordion({ active:activeAcc,autoHeight: false});
	
	} else {
			// else open correct accordion section or leave default depending on hash being present or not
			$("#accordion").accordion({ active:activeAcc,autoHeight: false,change: function(event, ui) { $(window).scrollTo($('.ui-state-active'), 400 ) }});
			// if a sub section with a anchor exist then scroll that anchor after accordion has opened correct section
			if(activeAccSubSection){
				$(window).scrollTo($('#'+activeAccSubSection[1]), 800 );
			} else {
				// if no anchor within a sub section exist then scroll to open accordion
				$(window).scrollTo($('.ui-state-active'), 800 );
			}
	}
}




	// hash change
$('#content a').click(function(){
	theLink = false;
	theLink = $(this).attr('href');
	theLinkTest = theLink.indexOf('#');
	if(theLinkTest != '-1'){
		var splitHash = $(this).attr('href').split('#');
			// remove #
			var activeAcc=splitHash[1];
			// test to find subsection anchor
			activeAccSubSectionTest = activeAcc.indexOf('=');
			activeAccSubSection = false;
			// if test is true
			if(activeAccSubSectionTest != '-1'){
				// split the varibale example 2(accordion sub section) and animal(anchor within subsection)
				activeAccSubSection = activeAcc.split('=', [2]);
				// place sub section accordion varibale within activeAcc
				activeAcc = activeAccSubSection[0];
			}
			// test if activeAcc is either a number or text
			if(/^\d*$/.test(activeAcc)){
				activeAcc=parseInt(activeAcc);
				$(window).scrollTo($('body'), 800, function(){	
						$("#accordion").accordion( 'destroy' );
						$("#accordion").accordion({ active:activeAcc,autoHeight: false,change: function(event, ui) { $(window).scrollTo($('.ui-state-active'), 400 ) }});		
						// if a sub section with a anchor exist then scroll that anchor after accordion has opened correct section
						if(activeAccSubSection[1]){
							$(window).scrollTo($('#'+activeAccSubSection[1]), 800 );
						} else {
							// if no anchor within a sub section exist then scroll to open accordion
							$(window).scrollTo($('.ui-state-active'), 800 );
						}
				});
			} else {
				// if #hash change was for a anchor within already open accordion then just go the right anchor without any accodion effect 
				$(window).scrollTo($('#'+activeAcc), 800 );
			}
	}		

});



                // SITEMAP
                $('ul#sitemap').hide();

                $('#sitemap_link').live("click",function(){

                    if ($(this).hasClass("sitemap_visible")){
                        $('ul#footer').css('border-bottom','none');
                        
                        
                           $(window).scrollTo( $('body'), 800, function(){$('ul#sitemap').hide();} );

                      




                        $(this).removeClass("sitemap_visible");


                    } else {
                        $('ul#footer').addClass('line');
                        $(this).addClass("sitemap_visible")
                    
                    
                    $('ul#sitemap').show(function(){
                       $(window).scrollTo( $('ul#sitemap'), 800 );

                    });
                    };
                    return false;
                });


                // END SITEMAP

                // Empty search
                $('#search_field').live('click',function(){
                   $(this).val("");
                });
                // end empty search

                


                 //HOMEPAGE ANIMATION

				/*

                 i=0;
                 fadeImg=$('#header_image').attr('class').split('?');

                 $('#header_image').append('<img src="'+fadeImg[0]+'" title="1" /><img src="'+fadeImg[1]+'" title="2" /><img src="'+fadeImg[2]+'" title="3" />')

                 // set up stack order of images
                 $('#header_image img').each(function(){
                    $(this).css('position','absolute');
                    $(this).css('display','block');
                 });


                 $('#header_image img').eq(0).css('z-index','2');
                 $('#header_image img').eq(1).css('z-index','1');
                 $('#header_image img').eq(2).css('z-index','0');




                 function changeHeaderImage() {
                      if (i==3){i=0};
                      $('#header_image img').eq(i).fadeOut('slow',function(){
                          $('#header_image img').each(function(){
                              
                              $(this).css('z-index',parseInt($(this).css('z-index'))+1);
                              if ($(this).css('z-index')>2){
                                  $(this).css('z-index','0');
                              };
                          });
                          $('#header_image img').not($('#header_image img').eq(i)).each(function(){
                              $(this).show();
                          });
                      });



                    i=i+1;
                    var t=setTimeout(changeHeaderImage,4000);
                 };
                 if ($('body').hasClass('home')){
                 var t=setTimeout(changeHeaderImage,4000);
                 };
                 //END HOMEPAGE ANIMATION
				*/


                 // png fix
                 $('*').timPng();


});





