/*******************************************************************************

WISHLIST widget developed by Jonathan Pritchard

VERSION: 0.5

SHOW: Ipex2010

Copyright 2009 Resolution Event Technology Ltd trading as Showplans

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.3 Implements conference features
- 0.5 Implements floating wishlist style (together with browser fixes) (merged with springfair 2010 wishlist code)
********************************************************************************/


/* INITIALISATION **************************************************************/
//window.addEvent('load',function(){wl_load(); wl_load_confs();});
//jQuery(document).ready(function(){
//    wl_load();
//    alert("hello");
//});

var wl_strStandCookieName = "ipex_wishlist";
var wl_strConfCookieName = "ipex_wishlist_conf";

function wl_init_all(){
    if(get_object("wl_list") != null){
        wl_load();
        wl_load_confs();
        wl_check_browser();
    }
}

function wl_add(exName, standNumber){

	//load list:
	var strStandList = getCookieValue(wl_strStandCookieName);
	//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(wl_strStandCookieName, strSerialisedStands, 'years', 255);
            //make sure the wishlist is open when something is added to it.
            var divExpandable = get_object("wl_divExpandable");
            divExpandable.style.visiblity = "visible";
            divExpandable.style.display = "block";
            //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();
	}

        wl_check_empty();
        return false;

}
function wl_add_conf(strTitle, strDate, strTime, confCode){
    	//the cookie ipex_wishlist_conf contains data in the following format:
        //title^^date^^time^^confCode##titile^^date^^time^^confCode##tit........
        
        //load list of conferences:
	var strConfList = getCookieValue(wl_strConfCookieName);
	//create the array that will hold stand numbers and exhibitor names while we process the data:
	var arrConfList = 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(strConfList){
		//deserialise into an array:
		arrConfList = strConfList.split("##");
		//check to see if this exhibitor is already in the array
		for(var i = 0; i < arrConfList.length; i++){
			//extract stand number from this element
			var thisConfCode = arrConfList[i].split("^^")[3];
			if(thisConfCode == confCode){
                                booExExists = true;
			}
		}
	}
	//if not: add to array
	if (booExExists == false){
            //this exhibitor is not already in the list
            arrConfList.push(strTitle + "^^" + strDate + "^^" + strTime + "^^" + confCode);
            //serialise the stand number array:
            var strSerialisedConfs = arrConfList.join("##");
            //update cookie
            writePersistentCookie(wl_strConfCookieName, strSerialisedConfs, 'years', 255);
            //make sure the wishlist is open when something is added to it.
            var divExpandable = get_object("wl_divExpandable");
            divExpandable.style.visiblity = "visible";
            divExpandable.style.display = "block";
            //add to wishlist
            get_object("wl_list_conf").innerHTML = get_object("wl_list_conf").innerHTML + "<a href='#' onclick='wl_remove_conf(this);return false;' id='wl_item_" + confCode + "' class='wl_item_conf'><span class='wl_item_conf_heading'>"+strDate+" "+strTime+"</span>" + strTitle + "</a>";
            //alert("jQuery('#wl_list_conf').html()="+jQuery("#wl_list_conf").html());
            //update wl position for ie6
            wl_check_browser();
	}

        wl_check_empty_conf();
        //alert("wl_add_conf()");

}

function wl_load(){
	//this function loads the users existing wishlist selections (if any)
	//load list:
        var strStandList = getCookieValue(wl_strStandCookieName);
        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("wl_divExpandable");
	divExpandable.style.visiblity = "hidden";
	divExpandable.style.display = "none";
        wl_check_empty();
}

function wl_check_empty(){
    var strStandList = getCookieValue(wl_strStandCookieName);
    if(strStandList == false){
        get_object("wl_list").innerHTML = "<span class='wl_no_stands' id='wl_no_stands'>No stands in your wishlist</span>";
    }else{
        if(get_object("wl_no_stands")){
            get_object("wl_list").removeChild(get_object("wl_no_stands"));
        }
        
    }
}

function wl_load_confs(){
    	//this function loads the users existing wishlist conference selections (if any)
        //the cookie ipex_wishlist_conf contains data in the following format:
        //title^^date^^time^^confCode##titile^^date^^time^^confCode##tit........
	//load list:
        var strConfList = getCookieValue(wl_strConfCookieName);
	if(strConfList){
		//there is a cookie
		var arrConfList = strConfList.split("##");
		for(var p = 0; p < arrConfList.length; p++){
			var arrConfItemDetails = arrConfList[p].split("^^");
                        var strTitle = arrConfItemDetails[0];
                        var strDate = arrConfItemDetails[1];
			var strTime = arrConfItemDetails[2];
                        var strConfCode = arrConfItemDetails[3];
			//jQuery("#wl_list_conf").html(jQuery("#wl_list_conf").html() + "<a href='#' onclick='wl_remove_conf(this);return false;' id='wl_item_" + strConfCode + "' class='wl_item_conf'>" + strTitle + " - " + strTime + "</a>");
                        get_object("wl_list_conf").innerHTML = get_object("wl_list_conf").innerHTML + "<a href='#' onclick='wl_remove_conf(this);return false;' id='wl_item_" + strConfCode + "' class='wl_item_conf'><span class='wl_item_conf_heading'>"+strDate+" "+strTime+"</span>" + strTitle + "</a>";
                        //alert("wl_load_confs(); added item...");
		}
	}
        wl_check_empty_conf();
}

function wl_check_empty_conf(){
    var strConfList = getCookieValue(wl_strConfCookieName);
    if(strConfList == false){
        get_object("wl_list_conf").innerHTML = "<span class='wl_no_stands' id='wl_no_confs'>No debates in your wishlist</span>";
    }else{
        if(get_object("wl_no_confs")){
            get_object("wl_list_conf").removeChild(get_object("wl_no_confs"));
        }
    }
}

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("ipex_wishlist");
        var strStandList = getCookieValue(wl_strStandCookieName);
	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("ipex_wishlist", strSerialisedNewStandList,'years',255);
            writePersistentCookie(wl_strStandCookieName, strSerialisedNewStandList, 'years',255);
            //update wl position for ie6
            wl_check_browser();
	}
	//remove the anchor in the wish lish
	get_object("wl_list").removeChild(e);

        wl_check_empty();

}

function wl_remove_conf(e){
    //the cookie ipex_wishlist_conf contains data in the following format:
    //title^^date^^time^^confCode##titile^^date^^time^^confCode##tit........
    
    //search for the confCode in our array of objects and remove
    var strConfCode = e.id.replace("wl_item_","");

    //var strConfList = getCookieValue("ipex_wishlist_conf");
    var strConfList = getCookieValue(wl_strConfCookieName);
    var arrNewConfList = new Array();

    if(strConfList){
            //there is a cookie
            var arrConfList = strConfList.split("##");
            for(var p = 0; p < arrConfList.length; p++){
                    if(arrConfList[p].split("^^")[3] != strConfCode){
                            arrNewConfList.push(arrConfList[p]);
                    }
            }
            var strSerialisedNewConfList = arrNewConfList.join("##");
            //writePersistentCookie("ipex_wishlist_conf", strSerialisedNewConfList,'years',255);
            writePersistentCookie(wl_strConfCookieName, strSerialisedNewConfList, 'years',255);
            wl_check_browser();
    }
    //remove the anchor in the wish lish
    get_object("wl_list_conf").removeChild(e);

    wl_check_empty_conf();

}

function wl_goto_floorplan(){
        
        
        var strQSStands = "";
	var strQSConfs = "";

        var strStandList = getCookieValue(wl_strStandCookieName);
	if(strStandList){
		var arrStandList = strStandList.split("##");
		for(var s = 0; s < arrStandList.length; s++){
			if(s == arrStandList.length - 1){
				//last item in the list so no comma
				strQSStands += arrStandList[s].split("^^")[1];
			}else{
				strQSStands += arrStandList[s].split("^^")[1] + ",";
			}
		}


	}

        //the cookie ipex_wishlist_conf contains data in the following format:
        //title^^date^^time^^confCode##titile^^date^^time^^confCode##tit........

        //var strConfList = getCookieValue("ipex_wishlist_conf");
        var strConfList = getCookieValue(wl_strConfCookieName);
	if(strConfList){
		var arrConfList = strConfList.split("##");
		for(var c = 0; c < arrConfList.length; c++){
			if(c == arrConfList.length - 1){
				//last item in the list so no comma
				strQSConfs += arrConfList[c].split("^^")[3];
			}else{
				strQSConfs += arrConfList[c].split("^^")[3] + ",";
			}
		}


	}

        if(strQSStands != "" && strQSConfs != ""){
            window.open("http://www.showplans.com/ipex/index.php?stands=" + strQSStands + "&conf=" + strQSConfs, "showplanseventplanner",'width=1024,height=600,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
        }else if(strQSStands == "" && strQSConfs != ""){
            window.open("http://www.showplans.com/ipex/index.php?conf=" + strQSConfs, "showplanseventplanner",'width=1024,height=600,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
        }else if(strQSStands != "" && strQSConfs == ""){
            window.open("http://www.showplans.com/ipex/index.php?stands=" + strQSStands, "showplanseventplanner",'width=1024,height=600,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
        }else{
            window.open("http://www.showplans.com/ipex/index.php", "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("wl_divExpandable");
	if(divExpandable.style.display != "none"){
		divExpandable.style.visiblity = "hidden";
		divExpandable.style.display = "none";
                //get_object("wl_aShowHideToggle").innerHTML = "[+] Expand MyPlan";
                //jQuery("#wl_aShowHideToggle").css("background-position","0px 0px");
                get_object("wl_aShowHideToggle").style.backgroundPosition = "0px 0px";
	} else{
		divExpandable.style.visiblity = "visible";
		divExpandable.style.display = "block";
                //get_object("wl_aShowHideToggle").innerHTML = "[-] Hide MyPlan";
                //jQuery("#wl_aShowHideToggle").css("background-position","0px -20px");
                get_object("wl_aShowHideToggle").style.backgroundPosition = "0px -20px";
	}
        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 = wlContainer.offsetHeight;
    var arrWindowSize = [document.body.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 = (arrWindowSize[0] - arrScrollPosition[0] - 210 - get_object("PageBody_DIV").offsetLeft) + "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=/";
}


DomReady.ready(function(){wl_init_all();});
//jQuery(document).ready(function(){wl_init_all();});