/*******************************************************************************

WISHLIST widget developed by Jonathan Pritchard

Copyright 2009 Resolution Event Technology Ltd trading as Showplans

Version 0.1.01

NOTES:
- Wishlist data is stored in a two dimensional array in the form of: {{ex_name, stand_number},{ex_name, stand_number},{ex_name, stand_number},...}
- The array is serialised (sort of) into a string with the form: ex_name^^stand_nunber##ex_name^^stand_nunber##ex_name^^stand_nunber##ex_name^^stand_nunber##
- Initialisation (wl_load()) called at bottom of page.
- 0.1.01 implemented browser detection to fix position:fixed problem.
********************************************************************************/

function wl_add(exName, standNumber){
	
	//load list:
	var strStandList = getCookieValue("sf09_wishlist");
	//create the array that will hold stand numbers and exhibitor names while we process the data:
	var arrStandList = new Array();
	//create and initialise the boolean which indicates whether the selected exhibitor already exists in the array:
	var booExExists = false;
	//check to see if the cookie exists:
	if(strStandList){
		//deserialise into an array:
		arrStandList = strStandList.split("##");
		//check to see if this exhibitor is already in the array
		for(var i = 0; i < arrStandList.length; i++){
			//extract stand number from this element
			var standN = arrStandList[i].split("^^");
			if(standN[1] == standNumber){
				booExExists = true;
			}
		}
	}
	//if not: add to array
	if (booExExists == false){
		//this exhibitor is not already in the list
		arrStandList.push(exName + "^^" + standNumber);
		//serialise the stand number array:
		var strSerialisedStands = arrStandList.join("##");
		//update cookie
		writePersistentCookie("sf09_wishlist", strSerialisedStands,'years',255);
		//add to wishlist
		get_object("wl_list").innerHTML = get_object("wl_list").innerHTML + "<a href='#' onclick='wl_remove(this);return false;' id='wl_item_" + standNumber + "' class='wl_item'>" + exName + "</a>";
        //update wl position for ie6
        wl_check_browser();
	}
        var divExpandable = get_object("divExpandable");
        divExpandable.style.visiblity = "visible";
        divExpandable.style.display = "block";
        get_object("aShowHideToggle").innerHTML = "[-] Hide MyPlan";
}

function wl_load(){
	/*
	* Wishlist initialisation
	**/
	
	
	//load the users existing wishlist selections (if any)
	var strStandList = getCookieValue("sf09_wishlist");
	if(strStandList){
		//there is a cookie
		var arrStandList = strStandList.split("##");
		for(var p = 0; p < arrStandList.length; p++){
			var exName = arrStandList[p].split("^^")[0];
			var stNumber = arrStandList[p].split("^^")[1];
			get_object("wl_list").innerHTML = get_object("wl_list").innerHTML + "<a href='#' onclick='wl_remove(this);return false;' id='wl_item_" + stNumber + "' class='wl_item'>" + exName + "</a>";
		}
	}
	//hide the widget to begin with:
	var divExpandable = get_object("divExpandable");
	divExpandable.style.visiblity = "hidden";
	divExpandable.style.display = "none";
	        wl_check_browser();
}

function wl_remove(e){
	//search for the stand number in our array of objects and remove
	var stNum = e.id.replace("wl_item_","");
	
	var strStandList = getCookieValue("sf09_wishlist");
	
	var arrNewStandList = new Array();
	
	if(strStandList){
		//there is a cookie
		var arrStandList = strStandList.split("##");
		for(var p = 0; p < arrStandList.length; p++){
			if(arrStandList[p].split("^^")[1] != stNum){
				arrNewStandList.push(arrStandList[p]);
			}
		}
		var strSerialisedNewStandList = arrNewStandList.join("##");
		writePersistentCookie("sf09_wishlist", strSerialisedNewStandList,'years',255);
                wl_check_browser();
	}
	//remove the anchor in the wish lish
	var oWishList = get_object("wl_list");
	var oWishListItem = get_object(e.id);
	oWishList.removeChild(oWishListItem);
}

function wl_goto_floorplan(){
	//alert(strStandListCommaDel);
	var strStandList = getCookieValue("sf09_wishlist");
	if(strStandList){
		var arrStandList = strStandList.split("##");
		var strStandListCommaDel = "";
		for(var t = 0; t < arrStandList.length; t++){
			if(t == arrStandList.length - 1){
				//last item in the list so no comma
				strStandListCommaDel += arrStandList[t].split("^^")[1];
			}else{
				strStandListCommaDel += arrStandList[t].split("^^")[1] + ",";
			}
		}
		
		window.open("http://www.showplans.com/springfair2010/index.php?stands=" + strStandListCommaDel, "showplanseventplanner",'width=1024,height=600,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
	}
}

/************************************** DISPLAY FUNCTIONALITY *************************************/

function wl_ShowHide(){
	var divExpandable = get_object("divExpandable");
	if(divExpandable.style.display != "none"){
		divExpandable.style.visiblity = "hidden";
		divExpandable.style.display = "none";
                get_object("aShowHideToggle").innerHTML = "[+] Expand MyPlan";
	} else{
		divExpandable.style.visiblity = "visible";
		divExpandable.style.display = "block";
                get_object("aShowHideToggle").innerHTML = "[-] Hide MyPlan";
	}
        wl_check_browser();
}

function wl_check_browser(){
    //if the browser is old then set up window.onscroll event handler
    var browser=navigator.appName;
    //alert(b_version);
    if ((browser=="Microsoft Internet Explorer") && (vIE()<7)){
        //set wishlist box position to absolute
        get_object("wl_container").style.position = "absolute";
        //attach "scroll" event to window so that we can update the x and y positions on scroll.
        addEvent(window,"scroll", wl_position_fix);
        //attach "resize" event to window so that we can update the x and y positions on resize.
        addEvent(window,"resize", wl_position_fix);
        //set initial position of wishlist
        wl_position_fix();
        //alert(version);
    }
    
}

    function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;}


function wl_position_fix(){
    var wlContainer = get_object("wl_container");
    var containerHeight = get_object("divExpandable").offsetHeight + get_object("aShowHideToggle").offsetHeight;
    var arrWindowSize = [document.documentElement.clientWidth,document.documentElement.clientHeight]
    var arrScrollPosition = [document.documentElement.scrollLeft,document.documentElement.scrollTop];
    wlContainer.style.top = (arrScrollPosition[1] + arrWindowSize[1] - containerHeight - 5) + "px";
    wlContainer.style.left = (arrScrollPosition[0] + arrWindowSize[0] - 153) + "px";
}


/***************************************************************************
 ************************* Cross Browser addEvent **************************
 ***************************************************************************/

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

/***************************************************************************
 ************************* Cross Browser domReady **************************
 ***************************************************************************/

(function(){

    var DomReady = window.DomReady = {};

	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    

	var readyBound = false;	
	var isReady = false;
	var readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
        
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
            
	            readyList = [];
	        }
		}
	};

	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	};

	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
	
		readyBound = true;

		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}

		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();

		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}

		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			
				// and execute any waiting functions
				domReady();
			})();
		}

		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};

	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();
    
		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};
    
	bindReady();
	
})();
/***************************************************************************
 ********************** Cross Browser getElementByID ***********************
 ***************************************************************************/

function get_object(id) {
   var object = null;
   if( document.layers ) {
    object = document.layers[id];
   } else if( document.all ) {
    object = document.all[id];
   } else if( document.getElementById ) {
    object = document.getElementById(id);
   }
   return object;
  }

/***************************************************************************
 *************************** Cookie Utilities*******************************
 ***************************************************************************/
 
function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;

  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
     var year = expireDate.getYear();
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  }

  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}

/**********************************************************************************
 INITIALISATION
 **********************************************************************************/
DomReady.ready(function(){wl_load();});