var gMenuObj = [];
var gCurrentSelectedMenu = null;
var current_url;
var current_menu_ref;
var cssStyleOver = "background-image: url(images/small_green_vert_vig.gif);";
var cssStyleNormal = "background-image: url(images/small_black.gif);";
var contentDiv;
var firstLoadCompleted = false; // used to bring in muted version of animation
var preloadFlag = false; // not used but could be in the future
var imageArray = []; //for preloader
var haveMadeCatRequest = false;

		/*
		menuname = viewable text in menu item
		url = url of page loaded in via AJAX (also used as key for main_menu faux associative array)
		externalURL = url of exteral page loaded instead of content from this site
		secondItemURL = URL for second item to be loaded into page after main content
		secondItemDiv = name of DIV into which second item should be loaded
		css = when true we load external ccs. Its name is constructed from viewable text
		js = when true we load external javascript. Its name is constructed from viewable text
		jsfunc1 = js function to execute instead of loading external content via AJAX
		jsfunct2 = fires js function after external content is loaded 
		*/
	
var menulist = [
				
		{ menuname: "Home", url:"home.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:"load_offers", nonmenuItem:false },
		{ menuname: "Catalogue", url:"2010_catalogue.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false },
		{ menuname: "Quick Order", url:"qo.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:"display_qoform", jsfunc2:0, nonmenuItem:false },
		{ menuname: "Adidas", url:"adidas.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false },
		{ menuname: "Terms & Conditions",url:"terms_and_cond.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false },
		{ menuname: "Contact", url:"contact.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false },
		{ menuname: "Links", url:"links.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false },
		{ menuname: "Special Offers", url:"offers_smart_tabs.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:"initOffers", nonmenuItem:false },
		{ menuname: "Custom Clothing Designer", url:"custom_clothing/clothing_designer.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:"clothing_bindings", nonmenuItem:false },
		{ menuname: "Talk Sport", url:"talksport.html", externalURL:0, secondItemURL:0, secondItemDiv:0, css:0, js:0, jsfunc1:0, jsfunc2:0, nonmenuItem:false }
		];


function preloadImages() {
	if (document.images) {
		var imageArray = [
		["images/brochure_reflection.jpg"],
		["images/adidas_spread.jpg"],
		["images/view_cat_button_small_grey.png"],
		["images/nike_cat_spread.jpg"],
		["images/DACT_phone.png"],
		["images/fax_machine.png"],
		["images/macbook.png"],
		["images/hand_and_pen.png"],
		["images/flip_site_image.jpg"],
		["images/major_credit_debit_cards.png"],
		["images/harrod_logo.jpg"],
		["images/burnleypendlesoccerschools.jpg"],
		["images/tk_logo.jpg"],
		["images/lady_icon.jpg"],
		["images/white_panel_drop_shadow.png"],
		["images/710x342_white_background.png"]
		];
	var len = imageArray.length;
	var imageObj = new Image();
	 for(var i=0;i < len;i++) {
		imageObj.src = imageArray[i];
	 }
	 preloadFlag = true;
	 }
   }
	
	// entry point to the action!
	$(document).ready(function(){
	getValuesFromServer(); // load offers data - function in smart_tabs_display.js
	contentDiv = document.getElementById("contentDiv");
	var navcontainerDiv = document.getElementById("navcontainerDiv");
	var navlist = document.createElement("ul");// create unordered list element
	navlist.id = "navlist";
	var menuslength = menulist.length;
	for (var  i= 0; i < menuslength; i++){
	var this_menu_obj = new menu_constructor(i); // create an li object
	gMenuObj.push(this_menu_obj); // push onto gMenuObj
	navlist.appendChild(this_menu_obj.li);
	}
	navcontainerDiv.appendChild(navlist);
	// load Opera hacks css into doc head
		if(navigator.userAgent.indexOf("Opera")!=-1){
		var css = "css/opera.css"
		var fileref=document.createElement("link");
		fileref.setAttribute("media", "all");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("href", css);
		if (fileref!=""){
		document.getElementsByTagName("head").item(0).appendChild(fileref)
		}
		
		}
		
		//  jQuery slide bindings
		$('#close_talksport').bind('click', function() {
  		$("#talkSport").slideUp(300);
		});
		
		// Quick Order bindings
		
		$('#complete_qo_but').bind('click', function() {
		this.blur(); // stop persistant highlight of button
		qoRecalcTotal();
		$("#complete_order_formDiv").slideToggle(300);
		});
		
		$('#submit_qo').bind('click', function() {
		this.blur(); // stop persistant highlight of button
		submit_quick_order();
		});
		
		$('#hide_qo_form').bind('click', function() {
		$("#greyoutOverContentDiv").fadeOut(400);
		$("#quick_order_formDiv").slideUp(300);
		if(getElm("complete_order_formDiv").style.display == "block") $("#complete_order_formDiv").slideUp(300);
		});
		
		$('#hide_qo_complete_form').bind('click', function() {
		$("#complete_order_formDiv").slideUp(300);
		});
		
		$('#qo_newline').bind('click', function() {
		qoNewline(); return false;
		});
		// end Quick Order bindings
		
		current_menu_ref = gMenuObj[0]; // set to Home
		menu_highlight();
		window.location.hash = "home.html";// need to load Home page first.....
		pollHash();
		preloadImages();
		qo_setup();
		//newline(); // make first line in quick order form
	});
	
	function slide_talkSport(){
	$("#talkSport").slideToggle(300);
	}
	
	function slide_cat_order_form(){
	$("#order_cat_panel").slideToggle(300);
	}
	
	function display_qoform(){
	$("#greyoutOverContentDiv").css('filter', 'alpha(opacity=75)'); // hack for IE as it won't see it in CSS
	if(qoHasBeenSent) qo_setup(); // delete previous content and resets input form
	$("#greyoutOverContentDiv").fadeIn(400);
	$("#quick_order_formDiv").slideDown(300);	
	}

	function menu_constructor(i){
			this.anchor = top.document.createElement("a");// create anchor
			this.anchor.href= "#";
			if(menulist[i].nonmenuItem) this.anchor.style.cssText = "display: none;";
			this.menuname = menulist[i].menuname;
			this.url = menulist[i].url;
			this.externalURL = menulist[i].externalURL;
			this.secondItemURL = menulist[i].secondItemURL;
			this.css = menulist[i].css;
			this.js = menulist[i].js;
			this.jsfunc1 = menulist[i].jsfunc1;
			this.jsfunc2 = menulist[i].jsfunc2;
			this.anchor.onclick = function() {select_menu(menulist[i].url, menulist[i].menuname ); return false;}
			this.anchor.onmouseover = function() {this.style.cssText = cssStyleOver; if(current_menu_ref) kill_menu_highlight();};// change current menu item to 'normal' state
			this.anchor.onmouseout = function() {this.style.cssText = cssStyleNormal; menu_highlight()};
			this.li = top.document.createElement("li");
			var mytextnode = top.document.createTextNode(menulist[i].menuname);
			this.anchor.appendChild(mytextnode);
			this.li.appendChild(this.anchor);
			this.latch = function(){
			this.anchor.style.cssText = cssStyleOver;
			}
			this.delatch = function(){
			this.anchor.style.cssText = cssStyleNormal;
			}
	}
	
	function select_menu(url, menuname){
	if(menuname== "Talk Sport"){
	slide_talkSport();
	return;
	}
	if(menuname== "Quick Order"){
	display_qoform();
	return;
	}
	//obj.style.backgroundColor = "#009900";// dark green
	top.window.location.hash = url; // use 'top' to target Pencarrie page with menu in iframe
	}
	
	
	// change highlight of current menu item on mouseout
	function menu_highlight(){
	if(current_menu_ref) current_menu_ref.latch();
	}
	
	// change highlight of current menu item on mouseover
	function kill_menu_highlight(){
	if(current_menu_ref) current_menu_ref.delatch();
	}
		
	
	/* AJAX system for getting content */
	
	function pollHash(){
    window.setInterval("URL_listener()", 100);
    }
    
	function URL_listener(){
    if (window.location.hash != current_url){
    current_url = window.location.hash;
    get_content();
    }
	}
	
		
	function setupAJAX() {
	if (window.XMLHttpRequest) {
	  // If IE7/8, Mozilla, Safari, etc: Uses native XMLHttpRequest
	var ajaxRequest = new XMLHttpRequest();
	return ajaxRequest;
	} else {
	if (window.ActiveXObject) {
	  // ...otherwise, use the ActiveX control for IE5.x and IE6
	 var ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	 return ajaxRequest;
	  } else {
	alert("Sorry, this page won't work with this browser!\nYou need to upgrade to a recent version of\nFirefox, Safari, Opera or Internet Explorer.");
	
	  }
	 }
	}
	
	
	function get_content(){
	var url = current_url.substr(1);// get rid of hash symbol at front
	if(url.length == 0) return; // nothing to load!
	var ajaxRequest = setupAJAX();
	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",url+bustcacheparameter, true);
	//read returned data from server and place it in div
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200){
			if(gMenuObj[key].menuname == "Catalogue" || gMenuObj[key].menuname == "Custom Clothing Designer" ||  gMenuObj[key].menuname == "Adidas" ){
			contentDiv.style.padding = "0px";
			contentDiv.style.height = "535px";	
			}else{
			contentDiv.style.cssText = "padding: 20px 25px 30px 25px"; // compromised for T&C page
			contentDiv.style.height = "485px";
			}
			kill_menu_highlight(); // kill previous
			gMenuObj[key].latch(); // latch this menu item
			current_menu_ref = gMenuObj[key]; // and make it current
			contentDiv.innerHTML = ajaxRequest.responseText;
				if (gMenuObj[key].jsfunc2){
				try{
				var jsName = gMenuObj[key].jsfunc2;
				setTimeout(function(){ executeJS(jsName) } ,250); // delay to allow DOM to load
				}catch(e){
				content_missing(e, true);
				}
				}
				}else{
					content_missing(ajaxRequest.status, true);
					
				}
		}
		
	}
	   ajaxRequest.send(null);
	   // parse menus to find key
				var key = 0;
				for (var  i= 0; i < gMenuObj.length; i++){
				if(url == gMenuObj[i].url){
				key = i;
				break;
				}
				}
	}
	
	function content_missing(err, buttons){
		deleteprior(contentDiv);
		var errDiv = document.createElement("div");
		errDiv.style.cssText = "color: #99ccff; font-size: 16px; text-align: center;";
		var errMessage = "<p style='color: #99ccff; font-size: 16px;'>Sorry &#150; this content appears to be missing or there was a problem with your Internet connection</p>";
		errMessage+= "<br />Error "+err+"<br /><br /></div>";
		errDiv.innerHTML = errMessage;
		contentDiv.appendChild(errDiv);
			if(buttons){
			var try_again = document.createElement("input");
			try_again.setAttribute("type","button");
			try_again.setAttribute("value","Try again");
			try_again.style.cssText = "cursor: pointer;";
			try_again.onclick=function(){get_content();};
			errDiv.appendChild(try_again);
			// make reload Home button
			var reloadHome = document.createElement("input");
			reloadHome.setAttribute("type","button");
			reloadHome.setAttribute("value","or reload Home Page");
			reloadHome.style.cssText = "cursor: pointer;";
			reloadHome.onclick=function(){window.location.hash = "home.html";};
			errDiv.appendChild(reloadHome);	
			}

	
	}
	
	// special AJAX loader for Pencarrie page
	function loadPencarrie(){
	var url = "pencarrie.html";
	var ajaxRequest = setupAJAX();
	ajaxRequest.open("GET",url, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200){
				contentDiv.style.height = "800px";
				contentDiv.innerHTML = ajaxRequest.responseText;
				//document.getElementById("pancarrie_loader").style.display = "none";
				}
			}
		}
		 ajaxRequest.send(null);
	}
	/************* end AJAX system *************/
	
	function executeJS(js){
	eval(js+"()");// execute any special JS code after page loads	
	}
	
	function load_offers(){
	var flashvars = {};
	var params = {wmode: "transparent"};
	var attributes = {};
	//if(firstLoadCompleted){
	//swfobject.embedSWF("swf/cricket_offer_mute.swf", "offersDiv", "295", "535", "9.0.0", false, flashvars, params, attributes);
	//}else{
	swfobject.embedSWF("swf/ball_deals.swf", "offersDiv", "295", "535", "9.0.0", false, flashvars, params, attributes);
	//}
	swfobject.embedSWF("swf/flip_site_plug.swf", "flipcatPlugDiv", "112", "130", "9.0.0", false, flashvars, params, attributes);
	firstLoadCompleted = true;
	}
	
	// call from "more offers" button in animated ad on Home Page	
	function load_offers_page(){
	window.location.hash = "offers_smart_tabs.html";	
	}
	// call from "info" button in animated ad on Home Page	
	function load_balls_offer_page(){
	window.location.hash = "offers_smart_tabs.html";
	setTimeout(clickthrough, 500); // this fires the slide which then shows the ball offers
	}
	
	
	
	
	function request_cat(obj){
	var messageDiv = document.getElementById("messageDiv");

	if(haveMadeCatRequest){
	 messageDiv.innerHTML = "Sorry, you have already made a request this session.";
	 return;
	}
	var ajaxRequest = setupAJAX();// get ajaxRequestObject
	var cat_customer = escape(obj.their_name.value);	
	var cat_address = escape(obj.their_address.value.replace(/\r\n|\n/g,'<br>'));
	if(cat_customer == "" || cat_address == ""){
	messageDiv.innerHTML = "Sorry we need both your name and address in order to send your catalogue";	
	return;
	}
	var sendstring = 'cat_customer='+cat_customer+'&cat_address='+cat_address;
	ajaxRequest.open("POST", "php/cat_request.php", true); 
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//Wait for response
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		    if(ajaxRequest.status==200){
			var returned_message = ajaxRequest.responseText;
			haveMadeCatRequest = true;
			messageDiv.innerHTML = returned_message;
			}else{
            messageDiv.innerHTML = "Sorry, there was a server problem, please try again later";
			}
			
		}
	}
	ajaxRequest.send(sendstring);
		
		
	}
	
	
	function deleteprior(div){
	if(!div) return;
	while (div.firstChild){
    div.removeChild(div.firstChild);
 	}
	}
	
//Debug aid
   function WriteText(text){
	var div=document.getElementById("debug")
	var textnode=document.createTextNode(text)
	div.appendChild(textnode)

	}
	

	