// -----------------------------------------------------------------------------------
//
//	Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com
//	3/31/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

	Table of Contents
	-----------------
	Configuration
	Global Variables

	Extending Built-in Objects	
	- Object.extend(Element)
	- Array.prototype.removeDuplicates()
	- Array.prototype.empty()

	Lightbox Class Declaration
	- initialize()
	- start()
	- changeImage()
	- resizeImageContainer()
	- showImage()
	- updateDetails()
	- updateNav()
	- enableKeyboardNav()
	- disableKeyboardNav()
	- keyboardAction()
	- preloadNeighborImages()
	- end()
	
	Miscellaneous Functions
	- getPageScroll()
	- getPageSize()
	- getKey()
	- listenKey()
	- showSelectBoxes()
	- hideSelectBoxes()
	- pause()
	- initLightbox()
	
	Function Calls
	- addLoadEvent(initLightbox)
	
*/
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var fileLoadingImage = "/wsimages/lightbox/loading.gif";		
var fileBottomNavCloseImage = "/wsimages/lightbox/closelabel.gif";

var resizeSpeed = 7;	// controls the speed of the image resizing (1=slowest and 10=fastest)

var borderSize = 8;	//if you adjust the padding in the CSS, you will need to update this variable

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;

if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
		element = $(element);
		element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {
	
	initialize: function() {	

	},
	
	start: function(action,obj,postAjaxLoadfn) {	
		
		jQuery("#viddlerVideo").css("display","none");
		
		hideSelectBoxes();
		dataParams = "";
	
		if($j(obj).attr("dataParams")){
			dataParams = $j(obj).attr("dataParams");
		}

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setHeight('overlay', arrayPageSize[1]);
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.70 });

		// if image is NOT part of a set..

		// calculate top offset for the lightbox and display 
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = ((arrayPageSize[3] - 437) / 2) + arrayPageScroll[1];

		Element.setTop('lightbox', lightboxTop);
		Element.show('lightbox');
		if(action!='error'){
			document.getElementById('lbTitle').innerHTML = "";
			document.getElementById('lightBoxData').innerHTML =	'<div style="display: none;" id="loading"><h2>Loading data, please wait...</h2><a href="#" id="loadingLink" onClick="myLightbox.end(); return false;"><img src="/wsimages/ajaxLoaderBig.gif" alt="Nothing" /></a></div>';
		}	
		this.loadLB(action,dataParams,postAjaxLoadfn);
	},

	//
	//	loadLB()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	//	UPDATE (Tom Hoffmann): Function changed to loadLB.
	//
	loadLB: function(action,dataParams,postAjaxLoadfn) {	
	
		// hide elements during transition
		if(action!='error'){
			Element.hide('loading');
		}
		Element.hide('lbWrapper');
		Element.hide('lbTop');
		Element.hide('lightBoxDataContainer');
	
		myLightbox.showLBContainer(action,dataParams,postAjaxLoadfn);
	},

	//
	//	showImageContainer()
	//
	showLBContainer: function(action,dataParams,postAjaxLoadfn) {

		new Effect.Parallel(
			[ new Effect.Appear('lbTopImg', {sync: true}),
			  new Effect.Appear('lbBottomImg', {sync: true}),
				new Effect.Appear('lbWrapper', { sync: true }),
			  new Effect.Appear('lbTop', {sync: true}),
			  new Effect.Appear('lightBoxDataContainer', {sync: true}) ], 
			{ delay: 0.2, duration: .5 } 
		);
		if(action!='error'){
			new Effect.Appear('loading', { duration: 1, delay: 1.5});
			ajaxLoadLB(action,dataParams,postAjaxLoadfn);
		}
	},
	
	//
	//	end()
	//
	end: function() {
		new Effect.Parallel(
			[ 
			  new Effect.Fade('lbTopImg', {sync: true}),
			  new Effect.Fade('lbBottomImg', {sync: true}),
			  new Effect.Fade('lbTop', {sync: true}),
			  new Effect.Fade('lightBoxDataContainer', {sync: true}),
			  new Effect.Fade('lbWrapper', { sync: true})], 
			{ duration: 0.2 } 
		);
		new Effect.Fade('overlay', { duration: 0.2, delay: 0.2 });
		showSelectBoxes();
		jQuery("#viddlerVideo").css("display","block");

	}
}

// -----------------------------------------------------------------------------------

//
// ajaxLoadLB()
// communicates with mxAjax libraries to execute a CF method
// to return product information
//

function ajaxLoadLB(action,dataParams,postAjaxLoadfn){			
	// define the url
	
	ajaxURL = "/ajax/lbAction.cfm?action="+action+dataParams;	
	new Ajax.Request(ajaxURL, {
		method: 'get',
		onSuccess: function (response) {
			parseAjaxLBContent(response.responseText.evalJSON(),action,postAjaxLoadfn);
		},
		onFailure: function (response) {
			 alert("status: " + response.status + "; statusText: " + response.statusText + "; ");
		}
	});
	
}

function parseAjaxLBContent(responseObj,action,postAjaxLoadfn){
	SHTML = responseObj.SHTML;
	STITLE = responseObj.STITLE;
	STITLECLASS = responseObj.STITLECLASS;
	document.getElementById("lbTitle").innerHTML = "<h1 class='"+STITLECLASS+"'>"+STITLE+"</h1>";
	document.getElementById("lightBoxData").innerHTML = SHTML;
	if(postAjaxLoadfn){
		var j=setTimeout(postAjaxLoadfn,100);
	}
	if(action=='signin'){
		changeInputType(document.signinLoginForm.password,'text','password',false,true);
	}
	if(action=='newAccount'){
		changeInputType(document.signupLoginForm.password,'text','password',false,true);
	}
	
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	
// ---------------------------------------------------

function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

// ---------------------------------------------------


function joinQwoffHome(){
	myLightbox.start("newAccount","","joinQwoff('home')");
}

function checkleapyear(datea)
{
       datea = parseInt(datea);
        if(datea%4 == 0)
        {
                if(datea%100 != 0)
                {
                        return true;
                }
                else
                {
                        if(datea%400 == 0)
                                return true;
                        else
                                return false;
                }
        }
        return false;
}

// Join Qwoff Form Verification and AJAX stuff
function joinQwoff(origin){
	var emailFilter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	var alphaNumericRegex=/^[0-9A-Za-z]+$/; //^[a-zA-z]+$/
	if(origin=='home'){
		formObj = document.qwoffJoinFormHome;
		if(formObj.signupPassword.value == 'password'){
			formObj.signupPassword.value = '';	
		}
		if(formObj.signupEmail.value == 'email'){
			formObj.signupEmail.value = '';	
		}
		if(formObj.signupScreenName.value == 'screen name'){
			formObj.signupScreenName.value = '';	
		}
		document.qwoffJoinForm.signupEmail.value = formObj.signupEmail.value;
		document.qwoffJoinForm.signupPassword.value = formObj.signupPassword.value;
		document.qwoffJoinForm.signupScreenName.value = formObj.signupScreenName.value;
		document.qwoffJoinForm.day.value = formObj.day.value;
		document.qwoffJoinForm.month.value = formObj.month.value;
		document.qwoffJoinForm.year.value = formObj.year.value;
		document.qwoffJoinForm.signupTermsAgree.checked = true;
	} else {
		formObj = document.qwoffJoinForm;
	}
	errorHTML = "";
	sSignupEmail = formObj.signupEmail.value;
//	sSignupPasswordVerify = formObj.signupPasswordVerify.value;
	sSignupPassword = formObj.signupPassword.value;
	sSignupScreenName = formObj.signupScreenName.value;
	sSignupTermsAgree = formObj.signupTermsAgree.value;

	sDateOfBirthDay = formObj.day.value;	
	sDateOfBirthMonth = formObj.month.value;
	sDateOfBirthYear = formObj.year.value;
	

	// fix all input field classes back to normal if any are in error state
	document.getElementById("lbErrors").innerHTML = "";
	document.getElementById("signupEmail").className = "standardField";
//	document.getElementById("signupPasswordVerify").className = "standardField";
	document.getElementById("signupPassword").className = "standardField";
	document.getElementById("signupScreenName").className = "standardField";
	document.getElementById("dateofbirth").className = "standardField";
	document.getElementById("signupTermsAgree").className = "standardField";
	
	// Check the fields for correct data
	
	
	
	if(!emailFilter.test(sSignupEmail)){
		document.getElementById("signupEmail").className = "errorField";
		errorHTML = errorHTML+'<li>The email address entered is invalid, please correct it.</li>';
	}
	if(!alphaNumericRegex.test(sSignupPassword.value)){
		document.getElementById("signupPassword").className = "errorField";
//		document.getElementById("signupPasswordVerify").className = "errorField";
		errorHTML = errorHTML+'<li>The password entered contains non alpha-numeric characters, please correct it.</li>';							
	} else {
		if(sSignupPassword.length > 16 || sSignupPassword.length < 4){
			document.getElementById("signupPassword").className = "errorField";
//			document.getElementById("signupPasswordVerify").className = "errorField";
			errorHTML = errorHTML+'<li>The password entered needs to be between 4 and 16 characters.</li>';													
		} //else {
			//if(sSignupPasswordVerify!=sSignupPassword){
		//		document.getElementById("signupPassword").className = "errorField";
		//		document.getElementById("signupPasswordVerify").className = "errorField";
		//		errorHTML = errorHTML+'<li>The passwords do not match, please re-enter.</li>';							
		//	}
		//}
	}
	if(sSignupScreenName.length < 1){
		document.getElementById("signupScreenName").className = "errorField";
		errorHTML = errorHTML+'<li>The screen name entered needs to be between at least 1 character in length.</li>';													
	}
	
	if(sDateOfBirthDay.length==0 || sDateOfBirthMonth.length==0 || sDateOfBirthYear.length==0){
		errorHTML = errorHTML+'<li>The date of birth is invalid</li>';
		document.getElementById("dateofbirth").className = "errorField";
	} else{
		if(sDateOfBirthMonth == 4 || sDateOfBirthMonth == 6 || sDateOfBirthMonth == 9 || sDateOfBirthMonth == 11){
			if(sDateOfBirthDay > 30){
				errorHTML = errorHTML+'<li>The date of birth is invalid</li>';
				document.getElementById("dateofbirth").className = "errorField";				
			}
		} else{
			if(sDateOfBirthMonth == 2 && ((sDateOfBirthDay > 28 && !checkleapyear(sDateOfBirthYear))||(sDateOfBirthDay > 29 && checkleapyear(sDateOfBirthYear))) ){
				errorHTML = errorHTML+'<li>The date of birth is invalid</li>';
				document.getElementById("dateofbirth").className = "errorField";				
			}			
		}
	}
	
	if(sSignupTermsAgree.checked==false){
		errorHTML = errorHTML+'<li>You need to agree with the terms and conditions of qwoff by checking the box.</li>';
		document.getElementById("signupTermsAgree").className = "errorField";
	}	

	// Show errors or make ajax request
	if(errorHTML.length != 0){
		document.getElementById("lbErrors").innerHTML = '<h2>just a few errors:</h2><ul>'+errorHTML+'</ul>';							
	} else {
		ajaxURL = "?sSignupEmail="+sSignupEmail+"&sSignupPassword="+sSignupPassword+"&sSignupScreenName="+sSignupScreenName+"&sDOB="+sDateOfBirthDay+"/"+sDateOfBirthMonth+"/"+sDateOfBirthYear;
		ajaxURL = "/ajax/signup.cfm"+ajaxURL;
		document.getElementById("joinQwoffWrapper").style.display = "none";
		document.getElementById("joinQwoffAjaxLoader").style.display = "block";
		new Ajax.Request(ajaxURL, {
			method: 'get',
			onSuccess: function (response) {
				checkSignUpSuccess(response.responseText.evalJSON());	
			},
			onFailure: function (response) {
				 alert("status: " + response.status + "; statusText: " + response.statusText + "; ");
			}
		});					
	}
	
	return false;
}	

function checkSignUpSuccess(responseObj){

	SSUCCESS = responseObj.SUCCESS;
	SERRORMSG = responseObj.ERRORMSG;
	SHTML = responseObj.SHTML;
		
	if(SSUCCESS== false){
		document.getElementById("lbErrors").innerHTML = '<h2>just a few errors:</h2><ul>'+SERRORMSG+'</ul>';							
		document.getElementById("joinQwoffWrapper").style.display = "block";
		document.getElementById("joinQwoffAjaxLoader").style.display = "none";
	} else {
		document.getElementById("joinQwoffAjaxLoader").style.display = "none";			
		document.getElementById("joinQwoffWrapper").style.display = "block";
		document.getElementById("joinQwoffWrapper").innerHTML = SHTML;
		document.getElementById("lbTitle").innerHTML = "<h1>join qwoff success</h1>";
		
	}
}

