/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

//Event.observe(window, 'load', initialize, false);
var dwell_browser = navigator.appName;
//alert(dwell_browser);
if(dwell_browser == 'Microsoft Internet Explorer' || dwell_browser == 'Internet Explorer' ) {
	Event.observe(window, 'load', initialize, false);
}
else {
	Event.observe(window, 'dom:loaded', initialize, false);
}
Event.observe(window, 'load', getBrowserInfo, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
			//alert('initialize : 1');
			if ($('lbOnAuto')) {
					var lbOnAuto = $('lbOnAuto').value; 
					if (lbOnAuto) {
						this.content = lbOnAuto;
						//alert("initialize:" + browser);
						if (browser == 'Internet Explorer'){
							//alert("initialize scroll 1");
							this.getScroll();
							this.prepareIE('2600px', 'scroll');
							this.setScroll(0,0);
							this.hideSelects('hidden');
						}
						this.displayLightbox("block");
						$('lbOnAuto').value = '';
					} 
			}
			//alert('initialize : 2');
			this.atag = ctrl;
			if(ctrl.id.indexOf('lbOn-form-') >= 0)
			{
				//alert('initialize : 3');
				this.actType = 'form-submit';
				//alert(ctrl.id);
				//alert(document.getElementById(ctrl.id).form);
				//alert(document.getElementById(ctrl.id).form.action);
				this.content = (document.getElementById(ctrl.id)).form.action;
			}
			else if(ctrl.id.indexOf('lbOn-select-') >= 0)
			{
				//alert('initialize : 4');
				this.actType = 'select-onchange';
				this.content = (document.getElementById(ctrl.id)).form.action;
			}
			else
			{
				//alert('initialize : 5');
				this.actType = 'normal';
				this.content = ctrl.href;
			}
			//alert(this.actType);
			if(this.actType == 'select-onchange')
			{
				//alert('initialize : 6');
				//alert("onchange init");
				Event.observe(ctrl, 'change', this.activate.bindAsEventListener(this), false);
				//ctrl.onchange
				//alert(ctrl.onchange.body);
				//ctrl.onchange =  ctrl.onchange + ";//alert('works');// " + function(){return false;};
				//alert(ctrl.onchange);
			}
			else
			{
				//alert('initialize : 7');
				Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
				ctrl.onclick = function(){return false;};
			}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		//alert("activate:" + browser);
		if (browser == 'Internet Explorer'){
			//alert("activate scroll 2");
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		/*bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
		*/
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
	   /*
	    $('lightbox').className = "loading";	
		if(this.atag.id == 'lbOn-form')
		{
			//alert(this.atag.id);
			//alert(document.getElementById(this.atag.id).form);
			//alert(document.getElementById(this.atag.id).form.action);
			this.content = (document.getElementById(this.atag.id)).form.action;
		}
		//alert(this.content+"&email=ajay.setty@gmail.com");
		var myAjax = new Ajax.Request(
        this.content+"&email=ajay.setty@gmail.com",
        {method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
		*/
		//alert('loadInfo : 1');
		//alert('this.actType');
		if(this.actType == 'select-onchange')
		{
			if(this.atag.value == '#NA')
			{
				//alert("loadInfo:" + browser);
				if (browser == "Internet Explorer"){
					//alert("loadInfo scroll 3");
					this.setScroll(0,this.yPos);
					this.prepareIE("auto", "auto");
					this.hideSelects("visible");
				}

				this.displayLightbox("none");
				return;
			}
		}
		//alert('loadInfo : 2');
		$('lightbox').className = "loading";	
		//alert(this.actType);
		if(this.actType== 'form-submit')
		{
			if(!validateLbOnForm(this.atag.id))
			{
				//alert("loadInfo -form:" + browser);
				if (browser == "Internet Explorer"){
					//alert("loadInfo -form scroll 4");
					this.setScroll(0,this.yPos);
					this.prepareIE("auto", "auto");
					this.hideSelects("visible");
				}

				this.displayLightbox("none");
				return;
			}
			//alert(this.atag.id);
			//alert(document.getElementById(this.atag.id).form);
			//alert(document.getElementById(this.atag.id).form.action);
			this.content = (document.getElementById(this.atag.id)).form.action;
			var oForm = this.atag.form;
    		var sBody = getRequestBody(oForm);
    		//alert(sBody);
			var myAjax = new Ajax.Request(
	        this.content,
	        {method: 'post', parameters: sBody, onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}
		else if(this.actType == 'select-onchange')
		{
			this.content = (document.getElementById(this.atag.id)).form.action;
			//alert(this.content+"&email=ajay.setty@gmail.com");
			var oForm = this.atag.form;
    		var sBody = getRequestBody(oForm);
    		//alert(sBody);
			var myAjax = new Ajax.Request(
	        this.content,
	        {method: 'post', parameters: sBody, onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}
		else
		{
			//alert('loadInfo : 3');
			var myAjax = new Ajax.Request(
	        this.content,
	        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
			);
		}
	},
	
	// Display Ajax response
	processInfo: function(response){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		//alert(info);
		new Insertion.Before($('lbLoadMessage'), info)
		this.actions();		
		sleep(500);
		$('lightbox').className = "done";	
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		//alert('actions : 1');
		var pageUrl = window.location.href;
		var securePage = false; 
		if(pageUrl.indexOf("http://") >= 0) {
			securePage = false;
			//alert('unsecure - actions');
		}
		else {
			securePage = true;
			//alert('secure - actions');
		}
		//alert('actions : 2');

		lbActions = document.getElementsByClassName('lbAction');
		for(i = 0; i < lbActions.length; i++) {
			//alert('actions : 3-'+i);
			//alert(lbActions[i].id);
			//alert(lbActions[i].id.indexOf("lbAction-form-"));
			if(lbActions[i].id.indexOf("lbAction-form-") == -1)
			{
				//alert('init2- ' + jQuery('#'+lbActions[i].id).attr("href"));
				var linkHref = jQuery('#'+lbActions[i].id).attr("href"); 
				if(linkHref != null && linkHref != '')
				{
					if(securePage == true) {
							linkHref = linkHref.replace("http://","https://");
					}
					else {
						linkHref = linkHref.replace("https://","http://");
					}
					jQuery('#'+lbActions[i].id).attr("href",linkHref); 
					//alert('final2- ' + jQuery('#'+lbActions[i].id).attr("href"));
				}
			}
			else
			{
				//alert("Form Submit: " + lbActions[i].id);
				//alert("Formid : " + document.getElementById(lbActions[i].id));
			}
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}
		//alert('actions done');
	},
	
	actions_HIDE: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}
	},

	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));
	   $('lightbox').className = "loading";	
	   
 	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},
	
	// Example of creating your own functionality once lightbox is initiated
	insertForm: function(e){
	   //alert("insertForm");
	   Element.remove($('lbContent'));
	   //alert("insertForm 2");
	   $('lightbox').className = "loading";	
	   //alert("insertForm 3a " + Event.element(e).id);
	   //alert("insertForm 3b " + Event.element(e).parentNode.id);
	   //alert("insertForm 3c " + Event.element(e).parentNode.form);
	   myForm = Event.element(e).form;
	   //alert("insertForm 4");
	   var oForm = myForm;
	   var sBody = getRequestBody(oForm);
	   //alert(sBody);
	   var myAjax = new Ajax.Request(
	   		myForm.action,
	  	 	{method: 'post', parameters: sBody, onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},

	// Example of creating your own functionality once lightbox is initiated
	login: function(e){
	   //alert(Event.element(e).form);
	   Event.element(e).form.submit();
	   //this.deactivate();
	},

	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));
		//alert("deactivate :" + browser);
		if (browser == "Internet Explorer"){
			//alert("deactivate 1");
			this.setScroll(0,this.yPos);
			//alert("deactivate 2");
			this.prepareIE("auto", "auto");
			//alert("deactivate 3");
			this.hideSelects("visible");
		}
		//alert("deactivate 4");
			
		this.displayLightbox("none");
	}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize_HIDE(){
	lbOnCheckElements = document.getElementsByClassName('lbOnCheck'); //document.getElementsByClassName("lbOnCheck");
	for(i = 0; i < lbOnCheckElements.length; i++) {
		if(document.getElementById("loginCheck") != 'undefined' && document.getElementById("loginCheck") != 'null' && document.getElementById("loginCheck").value == "1") {
			jQuery('#'+lbOnCheckElements[i].id).removeClass('lbOn');
		}
		else {
			jQuery('#'+lbOnCheckElements[i].id).addClass('lbOn');
		}
	}

	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

function initialize(){
	var pageUrl = window.location.href;
	var securePage = false; 
	//alert(pageUrl);
	//alert(pageUrl.indexOf("http://"));
	if(pageUrl.indexOf("http://") >= 0) {
	//if(pageUrl.indexOf("secure/") >= 0) {
		securePage = false;
		//alert('unsecure');
	}
	else {
		securePage = true;
		//alert('secure');
	}
	//alert('1-initialize: 1');
	lbOnCheckElements = document.getElementsByClassName('lbOnCheck'); //document.getElementsByClassName("lbOnCheck");
	for(i = 0; i < lbOnCheckElements.length; i++) {
		//alert('1-initialize: 1-' + i);
		if(document.getElementById("loginCheck") != 'undefined' && document.getElementById("loginCheck") != 'null' && document.getElementById("loginCheck").value == "1") {
			jQuery('#'+lbOnCheckElements[i].id).removeClass('lbOn');
		}
		else {
			jQuery('#'+lbOnCheckElements[i].id).addClass('lbOn');
			//alert('init- ' + jQuery('#'+lbOnCheckElements[i].id).attr("href"));
			var linkHref = jQuery('#'+lbOnCheckElements[i].id).attr("href"); 
			if(linkHref != null && linkHref != '')
			{
				if(securePage == true) {
					//linkHref.replace("secure/","");
					linkHref = linkHref.replace("http://","https://");
				}
				else {
					linkHref = linkHref.replace("https://","http://");
				}
				jQuery('#'+lbOnCheckElements[i].id).attr("href",linkHref); 
				//alert('final- ' + jQuery('#'+lbOnCheckElements[i].id).attr("href"));
			}
		}
	}
	//alert('1-initialize: 2');
	addLightboxMarkup();
	///alert('1-initialize: 3');
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		//alert('1-initialize: 4-'+i);
		//alert('init1 id- ' + lbox[i].id);
		//alert('init1- ' + jQuery('#'+lbox[i].id).attr("href"));
		var linkHref = jQuery('#'+lbox[i].id).attr("href"); 
		//alert('init1 sec- ' + securePage);
		if(linkHref != null && linkHref != '')
		{
			if(securePage == true) {
				linkHref = linkHref.replace("http://","https://");
			}
			else {
				linkHref = linkHref.replace("https://","http://");
			}
			jQuery('#'+lbox[i].id).attr("href",linkHref); 
			//alert('final1 lh - ' + linkHref);
			//alert('final1- ' + jQuery('#'+lbox[i].id).attr("href"));
		}
		valid = new lightbox(lbox[i]);
	}
	//alert('1-initialize: 4');
}




// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<span>Processing...</span>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}

function sleep(delay)
{
	//var start = new Date().getTime();
	//while (new Date().getTime() < start + delay);
}

function getRequestBody(oForm) 
{
	//alert('getRequestBody');
    var aParams = new Array();
    //alert('elem lenght' + oForm.elements.length);
    for (var i=0 ; i < oForm.elements.length; i++) 
    {
    	//alert('getRequestBody-' + i);
		//alert('getRequestBody : ' +  oForm.elements[i].name);
        var sParam = encodeURIComponent(oForm.elements[i].name);
        sParam += "=";
        sParam += encodeURIComponent(oForm.elements[i].value);
        aParams.push(sParam);
    } 
    return aParams.join("&");
}

function validateLbOnForm(formId)
{
	if(formId == 'lbOn-form-nls')
	{
		return newsletterSubscriberFormDetail.submit();
	}
	if(formId == 'lbOn-form-ppatc')
	{
		return productAddToCartForm.submitAddToCart();
	}
	if(formId == 'lbOn-form-zipcode')
	{
		return usZipCodeSearch.submit();
	}
	if(formId == 'lbOn-form-ca-zipcode')
	{
		return caZipCodeSearch.submit();
	}
	return true;
}
