//////////////////////////////////////////////////////
// Chron objects                                    //
//////////////////////////////////////////////////////
function timerObj() {
    this.startTime = (new Date()).getTime();
    this.stopTime = 0;
    this.splitTime = 0;

    this.start = function() {
	this.startTime = (new Date()).getTime();
    }
    this.stop = function() {
	this.stopTime = (new Date()).getTime();
    }
    this.elapsed = function() {
	if (this.stopTime == 0) {
	    this.stop();
	}
	return this.stopTime - this.startTime;
    }
    this.split = function() {
	this.splitTime = (new Date()).getTime() - this.startTime;
	return this.splitTime;
    }
    this.diff = function() {
	if (this.split == 0) {
	    return this.split();
	} else {
	    var oldSplitTime = this.splitTime;
	    return this.split() - oldSplitTime;
	}
    }
}
// Scheduler (requires timer)
function ChronometerTask(workFunction, callbackFunction, interval_ms, maxIteration) {
    this.workFunction = workFunction;
    this.callbackFunction = callbackFunction;
    this.interval = interval_ms;
    this.startTime = 0;
    this.lastTime = 0;
    this.maxIteration = maxIteration;
    this.counter = 0;
    var executionInterval = 0;
    this.checkTime = function(currentTime, currentTaskId) {
	if (this.lastTime == 0) {
	    this.startTime = currentTime;
	    this.lastTime = this.startTime;
	}
	if (currentTime - this.lastTime >= interval_ms) {
	    this.counter++;
	    this.lastTime = currentTime;
	    eval(workFunction);
	}
	if (this.maxIteration > -1 && this.counter >= this.maxIteration) {
	    this.destroy(currentTaskId);
	}
    }
    this.pause = function(pause_ms) {
        
    }
    this.destroy = function(currentTaskId) {
	if (this.callbackFunction && this.callbackFunction != null && this.callbackFunction.length > 0) {
	    eval(callbackFunction);
	}
	delete pageChronometer.tasks[currentTaskId];
    }
}
// pageChronometer.tasks['test'] = new ChronometerTask("console.append(\'test\');", null, 100, 10);
        
//////////////////////////////////////////////////////
// Singleton declarations                           //
//////////////////////////////////////////////////////
var	pageStopwatch = new function() {	// singleton page stopwaqtch
	this.obj = new timerObj();
    }
    var pageChronometer = new function() { // page Chronometer singleton
	    // configuration parameters
	    this.DISPLAY_WINDOW_STATUS = false; // show status in window status
	    this.SLEEP_THRESHOLD = 0; // number of tasks in the page tasks array beyond which to consider sleeping -- should be 0
	    this.SLEEP_TIME = 2500; // number of ms to wait after first loading for nothing to happen before going to sleep
	    this.UPDATE_INTERVAL_MS = 40; // milliseconds to update the chronometer -  >40 ms recommended
	    this.REM_CYCLE_MS = 500; // milliseconds to update the chronometer in sleep mode
	    this.MAX_EXECUTION_TIME = -1; // if <=0, infinite execution

	    // object properties
	    this.time = 0;
	    this.startTime = 0;
	    this.peakLag = 0; // the interval will try to catch up with real time.  peakLag will measure max lag
	    this.tasks = new function() {} // task singleton leave empty for associate task array
		this.pageLoaded = false;
	    this.interval_id = -1;
	    this.sleeping = false;
	    this.init = function() {
		this.interval_id = setInterval('pageChronometer.updateTime()', this.UPDATE_INTERVAL_MS);
		this.sleeping = false;
		this.startTime = (new Date()).getTime();
	    }
		this.checkInterval = function() {// this will change the interval to sleep cycle if there are no tasks after initial 2000ms initialization period
		    if (this.REM_CYCLE_MS > this.UPDATE_INTERVAL_MS && this.time > this.SLEEP_TIME) {
			if (!this.sleeping && this.taskCount() == this.SLEEP_THRESHOLD) {
			    // all tasks complete
			    this.sleep();
			} else if (this.sleeping && this.taskCount() > this.SLEEP_THRESHOLD) {
			    // task was added while sleeping
			    this.wakeUp();
			}
		    }
		}
		    this.wakeUp = function() {
			window.clearInterval(this.interval_id);
			this.init();
		    }
			this.sleep = function() {
			    window.clearInterval(this.interval_id);
			    this.sleeping = true;
			    this.time -= this.UPDATE_INTERVAL_MS;
			    this.interval_id = setInterval('pageChronometer.updateTime()', this.REM_CYCLE_MS);
			}
			    var triggerLock = false;
	    this.updateTime = function() {
		this.checkInterval();
		if (this.sleeping) {
		    this.time += pageChronometer.REM_CYCLE_MS;
		} else {
		    this.time += pageChronometer.UPDATE_INTERVAL_MS;
		}
		if (this.MAX_EXECUTION_TIME > 0) {
		    if (this.time > this.MAX_EXECUTION_TIME) {
			this.kill();
			triggerLock = true;
		    }
		}
		if (!triggerLock) {
		    this.trigger();
		}
		if (this.DISPLAY_WINDOW_STATUS) {
		    nightRider.flash(this.time);
		}
	    }
		this.currentTask = null;
	    this.trigger = function() {
		// do stuff
		if (!this.pageLoaded) {
		    try {
			pageInit(); // do not load page init until the page is loaded
			this.pageLoaded = true;
		    } catch (le) {
			debug_console.append('page could not be fully loaded : terminal javascript error : ' + le);
			// shut down the chronometer
			this.pageLoaded = false;
			this.kill();
		    }
		}
		if (this.pageLoaded) {
		    for (var i in this.tasks) {
			delete this.currentTask;
			this.currentTask = this.tasks[i];
			this.tasks[i].checkTime(this.time,i);
		    }
		}
	    }
		var tmpTaskCount;
	    this.taskCount = function() {
		tmpTaskCount = 0;
		for (var i in this.tasks) {
		    tmpTaskCount++;
		}
		return tmpTaskCount;
	    }
		var elapsedTime = 0;
	    var lag = 0;
	    this.getLag = function() { // this gives a measure of how many seconds the chronometer is off the absolute time due to delays caused by scripts.  Should optimize trigger intervals to minimize this value.
		// the page chronometer time should always be <= real time
		elapsedTime = (new Date()).getTime() - this.startTime;
		lag = elapsedTime - this.time;
		if (lag > this.peakLag) {
		    this.peakLag = lag;
		}
		return lag;
	    }
		this.kill = function() {
		    window.clearInterval(this.interval_id);
		}
		    this.addTask = function(newTask, newTaskId) {
			if (this.sleeping == true) {
			    this.wakeUp();
			}
			if (!newTaskId) {
			    newTaskId = 'auto_task_' + generateRandomNumWord(8, 'upper');
			}
			this.tasks[newTaskId] = newTask;
		    }
	}

    var ua = new function() { // user agent singleton
	    var u = navigator.userAgent, d = document;
	    this.dom = (typeof d.getElementById != "undefined") && (typeof d.createElement != "undefined");
	    this.safari = /Safari/.test(u);
	    this.opera = /Opera/.test(u);
	    this.konqueror = /Konqueror/.test(u);
	    this.ie = (typeof d.all != "undefined") && (!this.safari && !this.opera && !this.konqueror);
	};
         
var debug_console = new function() { // page console for debugging
	this.divObj = document.getElementById("console");
	this.init = function() {
	    this.divObj = document.getElementById("console");
	    if (!this.divObj) {
                if (parent.document.getElementById("console")) {
                    this.divObj = parent.document.getElementById("console");
                } else {
                    alert("Missing console layer");
                }
	    }
	}
	    var newline = null;
        var appendTxt = null;
        this.append = function(data) {
	    if (!this.divObj) {
		this.init();
	    }
	    newline = document.createElement("div");
	    this.divObj.appendChild(newline);
	    appendTxt = document.createTextNode(data);
	    newline.appendChild(appendTxt);
	}
	    this.render = function(data) {
		if (!this.divObj) {
		    this.init();
		}
		this.divObj.innerHTML = data;
	    }
    }

    var windowDimensionObj = new function () {
	    this.getWidth = function() {
		if( typeof( self.innerWidth ) == 'number' ) {
		    //Non-IE
		    return self.innerWidth;
		} else if( document.documentElement && document.documentElement.clientWidth ) {
		    //IE 6+ in 'standards compliant mode'
		    return document.documentElement.clientWidth;
		} else if( document.body && document.body.clientWidth) {
		    //IE 4 compatible
		    return document.body.clientWidth;
		} else {
		    return 640;
		}
	    }
		this.getHeight = function() {
		    if( typeof( self.innerWidth ) == 'number' ) {
			//Non-IE
			return self.innerHeight;
		    } else if( document.documentElement && document.documentElement.clientWidth ) {
			//IE 6+ in 'standards compliant mode'
			return document.documentElement.clientHeight;
		    } else if( document.body && document.body.clientWidth) {
			//IE 4 compatible
			return document.body.clientHeight;
		    } else {
			return  480;
		    }
		}
	}

    var nightRider = new function() {
	    var nightRiderCounter = 0;
	    var nightRiderDisplayArr = new Array();
	    nightRiderDisplayArr[0] = '\\---------';
	    nightRiderDisplayArr[1] = '-\\--------';
	    nightRiderDisplayArr[2] = '--\\-------';
	    nightRiderDisplayArr[3] = '---\\------';
	    nightRiderDisplayArr[4] = '----\\-----';
	    nightRiderDisplayArr[5] = '-----\\----';
	    nightRiderDisplayArr[6] = '------\\---';
	    nightRiderDisplayArr[7] = '-------\\--';
	    nightRiderDisplayArr[8] = '--------\\-';
	    nightRiderDisplayArr[9] = '---------\\';
	    nightRiderDisplayArr[10] = '---------/';
	    nightRiderDisplayArr[11] = '--------/-';
	    nightRiderDisplayArr[12] = '-------/--';
	    nightRiderDisplayArr[13] = '------/---';
	    nightRiderDisplayArr[14] = '-----/----';
	    nightRiderDisplayArr[15] = '----/-----';
	    nightRiderDisplayArr[16] = '---/------';
	    nightRiderDisplayArr[17] = '--/-------';
	    nightRiderDisplayArr[18] = '-/--------';
	    nightRiderDisplayArr[19] = '/---------';
	    this.flash = function(thisTime) {
		nightRiderCounter = nightRiderCounter%(nightRiderDisplayArr.length);
		window.status = nightRiderDisplayArr[nightRiderCounter] + ' lag = ' + pageChronometer.getLag() + ' peak == ' + pageChronometer.peakLag;
		nightRiderCounter++;
	    }

	}


//////////////////////////////////////////////////////
// Static Methods                                   //
//////////////////////////////////////////////////////
    function trimString(sInString) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
}
    
    function checkNumber(theNumCandidate){
        var anum=/(^\d+$)|(^\d+\.\d+$)/
	    if (anum.test(theNumCandidate)) {
		return true;
	    } else {
		return false;
	    }
    }
    
function validStringNum(testString) {
    var value = true;
    var notValidChars = /[^a-zA-Z0-9]/;
    return !notValidChars.test(testString);
}
    
function getKeyEventCharacterCode(e, returnCharacterType) { // returnCharacterType = 'character' or 'decimal'
    var pressedKey;
    if (document.all)    { e = window.event; }
    if (e.keyCode) {
	pressedKey = e.keyCode;
    } else if (e.which) {
	pressedKey = e.which;
    } else {
	return;
    }
    pressedCharacter = String.fromCharCode(pressedKey);
    // alert(' Character = ' + pressedCharacter + ' [Decimal value = ' + pressedKey + ']');

    if (returnCharacterType == 'character') {
	if (pressedCharacter) {
	    return pressedCharacter;
	}
    } else if (returnCharacterType == 'decimal') {
	if (pressedKey) {
	    return pressedKey;
	}
    } else {
	alert('getKeyEventCharacterCode() Error : Malformed return character type == ' + returnCharacterType);
    }
    return false;
}

function printWindow(){
    if (is.v >= 4) {
	window.print();
    } else {
	alert('The current computer does not support this print button.  Please use the browser print function from the file menu.');
    }
}

function generateRandomInt(maxRand) {
    if (!maxRand) {
	maxRand = 10000000000000000;
    } else {
	maxRand++;
    }
    var ranNum= Math.floor(Math.random()*maxRand);
    return ranNum;
}
var alphabetArray = new Array(
			      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
			      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
			      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
			      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
			      );
    
// generates random word with characters limit
function generateRandomWord(characters, alpha_case) {
    var randWord = '';
    for (var i=0; i<characters; i++) {
	randWord += alphabetArray[generateRandomInt(alphabetArray.length - 1)];
    }
    if (alpha_case) {
	if (alpha_case.toLowerCase() == 'lower') {
	    randWord = randWord.toLowerCase();
	} else if (alpha_case.toLowerCase() == 'upper') {
	    randWord = randWord.toUpperCase();                
	}
    }
    return randWord;
}
function generateRandomNumWord(characters, alpha_case) {
    // this function a word with 50% number and 50% letters (on average)
    var randWord = '';
    for (var i=0; i<characters; i++) {
	if(generateRandomInt(1) == 1) {
	    randWord += alphabetArray[generateRandomInt(alphabetArray.length - 1)];
	} else {
	    randWord += generateRandomInt(9);
	}
    }
    if (alpha_case) {
	if (alpha_case.toLowerCase() == 'lower') {
	    randWord = randWord.toLowerCase();
	} else if (alpha_case.toLowerCase() == 'upper') {
	    randWord = randWord.toUpperCase();                
	}
    }
    return randWord;
}

var RegexFilters = new function() {
        this.zipCode = /[0-9]{5}((-)[0-9]{4,5})?/;
        this.currencyFilter= /\$\d{1,3}(,\d{3})*\.\d{2}/; // $17.23 or $14,281 or 545.45
        this.internationalPhoneFilter = /^\d(\d|-){7,20}/; // International Phone Number
        this.ipAddressFilter = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
        this.date = dateFilter = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/; // xx/xx/xxxx
        this.stateShortFilter = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i; // State Abbreviation
        this.socialSecurityFilter = /^\d{3}\-\d{2}\-\d{4}$/; // xxx-xx-xxxx
        this.phoneFilter = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
        this.emailFilter = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)|[0-9]{1,3})(\]?)$/; // a@b.com or a@127.0.0.1 or a@b.co.kr
    }
    function regexTest(regexFilter,testString) {
    if (regexFilter == '') {
	alert('Testing filter is empty.');
	return false;
    }
    if (testString == '') {
	alert('Test string is empty.');
	return false;
    }
    return regexFilter.test(testString);
}

    function validateEmail(formId) {
        var formObj = document.getElementById(formId);
        if (formObj && formObj.value !=  '') {
            if (regexTest(RegexFilters.emailFilter, formObj.value)) {
                return true;
            } else {
                alert("The email entered (" + formObj.value + ") is invalid.");
            }
        } else {
            alert("Please enter a valid email.");
        }
        return false;
    }
//////////////////////////////////////////////////////
// Static GUI Methods                               //
//////////////////////////////////////////////////////

function hideObject(strId) {
    var visObj = document.getElementById(strId);
    if (visObj) {
	visObj.style.display = 'none';
    }
}

function showObject(strId) {
    var visObj = document.getElementById(strId);
    if (visObj) {
	visObj.style.display = '';
    }
}
function preloadImages(thisImgArray) {
    if (document.images) {
	for(var loop = 0; loop < thisImgArray.length; loop++) {
	    var an_image = new Image();
	    an_image.src = thisImgArray[loop];
	}
    }
}
function toggleImages(thisDivImgStart, thisToggleImg_1, thisToggleImg_2) {
    thisDivImgStartObj = document.images[thisDivImgStart];
    var curImgSrc = thisDivImgStartObj.src;
    if (curImgSrc.indexOf(thisToggleImg_1) > 0) {
	thisDivImgStartObj.src = thisToggleImg_2;
    } else if (curImgSrc.indexOf(thisToggleImg_2) > 0) {
	thisDivImgStartObj.src = thisToggleImg_1;
    }
}

function toggleVisibility(visId) {
       
    var visObj = document.getElementById(visId);
    if (visObj) {
	if (visObj.style.display=='none') {
	    visObj.style.display = ''
		} else {
	    visObj.style.display = 'none'
		}
    }
}

function toggleCheckboxRadio(checkboxId) {
    var checkboxObj = document.getElementById(checkboxId);
    if (checkboxObj) {
	if (checkboxObj.checked) {
	    checkboxObj.checked = false;
	} else {
	    checkboxObj.checked = true;
	}
    }
}
function setClassName(objId, className) {
    if (document.getElementById(objId)) {
	document.getElementById(objId).className = className;
    }
}

function objectCoordinates(objCoordX, objCoordY, objTrueX, objTrueY) {
    this.x = objCoordX;
    this.y = objCoordY;
    this.xx = objTrueX; // includes scrolled space from left
    this.yy = objTrueY; // includes scrolled space from top
}

function getImageCoordinates(imageObjId, xOffset, yOffset) {
    var theObject = document.images[imageObjId];
    if (theObject == null) {
	return null;
    }

    if (imageObjId.indexOf('_right') != -1) {
	xOffset = xOffset - theObject.width;
    }
    theObject.style.position = "absolute"
        var objX = 0;
    var objY = 0;
    var objTX = 0;
    var objTY = 0;
    if (document.layers) {
	objX=theObject.x;
	objY=theObject.y;
	objTX=objX - window.pageXOffset;
	objTY=objY - window.pageYOffset;
    } else if (document.all) {
	objX=theObject.offsetLeft;
	objY=theObject.offsetTop;
	objTX=objX - document.body.scrollLeft;
	objTY=objY - document.body.scrollTop;
    } else {
	objX=theObject.offsetLeft;
	objY=theObject.offsetTop;
	objTX=objX - document.body.scrollLeft;
	objTY=objY - document.body.scrollTop;
    }
    objX+=xOffset;
    objY+=yOffset;
    objTX+=xOffset;
    objTY+=yOffset;
    theObject.style.position = "static";
    return new objectCoordinates(objX, objY, objTX, objTY);
}

function getAbsoluteTop() {
    if (document.layers) {
	return window.pageYOffset;
    } else if (document.all) {
	return document.body.scrollTop;
    } else {
	return document.body.scrollTop;
    }
}

function fade(initial_opacity, final_opacity, chronId) {
    var cronObj = pageChronometer.tasks[chronId];
    var fractionComplete = (cronObj.counter / cronObj.maxIteration);
    var opacityDelta = parseInt((final_opacity - initial_opacity)/cronObj.maxIteration);
    var nextOpacity = initial_opacity + (opacityDelta * cronObj.counter);
    changeOpac(nextOpacity, "popupMask");
}
function fadeIn() {
    var cronObj = pageChronometer.tasks['popupMaskFadeIn'];
    var nextOpacity = parseInt(((cronObj.maxIteration - cronObj.counter) / cronObj.maxIteration) * 100);
    changeOpac(nextOpacity, "popupMask");
    return true;
}
function fadeOut() {
    var cronObj = pageChronometer.tasks['popupMaskFadeIn'];
    var nextOpacity = parseInt(100 - ((cronObj.maxIteration - cronObj.counter) / cronObj.maxIteration) * 100);
    changeOpac(nextOpacity, "popupMask");
    return true;
}

function changeOpac(opacity, objectid) {
    var object = document.getElementById( objectid );
    changeObjOpac(opacity,object);
}
function changeObjOpac(opacity, obj) {
    var objStyle = obj.style;
    if (objStyle) {
	objStyle.opacity = (opacity / 100); 
	objStyle.MozOpacity = (opacity / 100); 
	objStyle.KhtmlOpacity = (opacity / 100); 
	objStyle.filter = "alpha(opacity=" + opacity + ")";
    }
}
function getOpac(objectid) {
    var object = document.getElementById( objectid ).style;
    object.visibility = "visible";
    if (object.opacity) {
	return parseFloat(object.opacity);
    } else if (object.MozOpacity){
	return parseFloat(object.MozOpacity);
    } else if (object.KhtmlOpacity){
	return parseFloat(object.KhtmlOpacity);
    } else if (object.filter){
	return 0.00;
    }
}
function getEventTarget(e) { // returns the mouseover or click event target object
    var targ;
    if (!e) var e = window.event;
    if (e.target) {
	targ = e.target;
    } else if (e.srcElement) {
	targ = e.srcElement;
    }
    if (targ && targ.nodeType == 3) { // defeat Safari bug
	targ = targ.parentNode;
    }
    return targ;
}
function removeChildNodes(divLayerId) {
    var divObj = document.getElementById(divLayerId);
    if (divObj) {
	while (divObj.hasChildNodes()) {
	    divObj.removeChild(divObj.firstChild);
	}
    }
}
function stopEventBubbling(e) {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

function isEnter(evt){
    var keyCode = null;

    if( evt.which ) {
	keyCode = evt.which;
    } else if( evt.keyCode ) {
	keyCode = evt.keyCode;
    }

    if( 13 == keyCode ) {
	return true
    }
    return false
}


$(document).ready(function(){
	TRK.validity.init();
    $("input[placeholder]").each(function(){
        $(this).placeholder();
    });
	TRK.news.init();
   
//    $("#newsletter_signup button").click(function(ev)	{
//    	ev.preventDefault();
//    	form = $(this).parents('form');
//    	output = TRK.ajax.post($(form).serialize());
//    	output.success(function(data) {
//    		console.log(data);
//    	});
//    });
});


var TRK = {
	//handler to wrap the common ajax requests
	ajax : {
		//careful if reassigning this, as all subsequent requests will point toward the new handler
		handler : rel_home+'/includes/ajaxHelper.php',// + "?version=" + Date.now(),
		
		//fires the ajax request for receiving html content 
		post : function( data, handler ){
			var self = this;	
			if(data === undefined) data = {};
			if(handler === undefined) handler = self.handler;
			return $.ajax({
				url : handler,
				type : "POST",
				cache : false,
				data : data
			});
		},
		
		utf8_encode : function(argString) {
			// Encodes an ISO-8859-1 string to UTF-8  
			// 
			// version: 1103.1210
			// discuss at: http://phpjs.org/functions/utf8_encode
			// +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
			// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// +   improved by: sowberry
			// +    tweaked by: Jack
			// +   bugfixed by: Onno Marsman
			// +   improved by: Yves Sucaet
			// +   bugfixed by: Onno Marsman
			// +   bugfixed by: Ulrich
			// *     example 1: utf8_encode('Kevin van Zonneveld');
			// *     returns 1: 'Kevin van Zonneveld'
			var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
			var utftext = "",
				start, end, stringl = 0;
		 
			start = end = 0;
			stringl = string.length;
			for (var n = 0; n < stringl; n++) {
				var c1 = string.charCodeAt(n);
				var enc = null;
		 
				if (c1 < 128) {
					end++;
				} else if (c1 > 127 && c1 < 2048) {
					enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
				} else {
					enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
				}
				if (enc !== null) {
					if (end > start) {
						utftext += string.slice(start, end);
					}
					utftext += enc;
					start = end = n + 1;
				}
			}
		 
			if (end > start) {
				utftext += string.slice(start, stringl);
			}
		 
			return utftext;
		},
		
		base64_encode : function(data) {
			// Encodes string using MIME base64 algorithm  
			// 
			// version: 1103.1210
			// discuss at: http://phpjs.org/functions/base64_encode
			// +   original by: Tyler Akins (http://rumkin.com)
			// +   improved by: Bayron Guevara
			// +   improved by: Thunder.m
			// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// +   bugfixed by: Pellentesque Malesuada
			// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// -    depends on: utf8_encode
			// *     example 1: base64_encode('Kevin van Zonneveld');
			// *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
			// mozilla has this native
			// - but breaks in 2.0.0.12!
			//if (typeof this.window['atob'] == 'function') {
			//    return atob(data);
			//}
			var self=this;
			var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
			var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
				ac = 0,
				enc = "",
				tmp_arr = [];
		 
			if (!data) {
				return data;
			}
		 
			data = self.utf8_encode(data + '');
		 
			do { // pack three octets into four hexets
				o1 = data.charCodeAt(i++);
				o2 = data.charCodeAt(i++);
				o3 = data.charCodeAt(i++);
		 
				bits = o1 << 16 | o2 << 8 | o3;
		 
				h1 = bits >> 18 & 0x3f;
				h2 = bits >> 12 & 0x3f;
				h3 = bits >> 6 & 0x3f;
				h4 = bits & 0x3f;
		 
				// use hexets to index into b64, and append result to encoded string
				tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
			} while (i < data.length);
		 
			enc = tmp_arr.join('');
		 
			switch (data.length % 3) {
			case 1:
				enc = enc.slice(0, -2) + '==';
				break;
			case 2:
				enc = enc.slice(0, -1) + '=';
				break;
			}
		 
			return enc;
		}
	},
	//Prints the content of any div or other container
	printWindow : function (strTitle, strContent) {
		
		if (strTitle == '') strTitle = "Bella Figura";
		if (strTitle === undefined) strTitle = "Bella Figura";
		
		var pdfrd =  new $.Deferred();
		
		var strFrameName = ("Bella_Print-" + (new Date()).getTime());
		var jFrame = $( "<iframe name='" + strFrameName + "'>" );
		
		jFrame
		.css( "width", "1px" )
		.css( "height", "1px" )
		.css( "position", "absolute" )
		.css( "left", "-9999px" )
		.appendTo( $( "body:first" ) );
		
		var objFrame = window.frames[ strFrameName ];
		var objDoc = objFrame.document;
		objDoc.open();
		objDoc.write( "<!DOCTYPE html>" );
		objDoc.write( "<head><title>" );
		objDoc.write( strTitle );
		objDoc.write( "</title></head><body>" );
		objDoc.write( strContent );
		objDoc.write( "</body></html>" );
		objDoc.close();
		
		objFrame.focus();
		objFrame.print();
		
		$(objFrame).remove();
		pdfrd.resolve();
		return pdfrd.promise();
	},
	
	//newsletter signup
	//meant for the media box input
	//perhaps want to broaden this to allow signup from other sections...ie shopping cart
	news : {
//		email : $("#emailSignup :input[type=email]"),
//		button : $("#emailSignupSubmit"),
	
		init : function(){
			this.email = $("#emailSignup :input[type=email]"),
			this.button = $("#emailSignupSubmit"),
			TRK.news.email.fireOnEnter(TRK.news.gather);
			TRK.news.button.live("click",function(ev){
				ev.preventDefault();
				TRK.news.gather();
			});
		},
		gather : function(){
			if(TRK.news.email.val() && TRK.news.email.val().indexOf("@") > 0) {
				TRK.news.add(TRK.news.email.val());
			}else{
				TRK.news.email.val('Please enter a valid email').attr("disabled",true).blur();
				setTimeout(function(){
					TRK.news.email.val("").attr("disabled",false).focus();
				},2000);
			}	
		},	
		add : function(addr){
			var params, req;
			params = {
				'function' : 'newsletter',
				'email' : TRK.news.email.val()
			}
			
			var req = TRK.ajax.post( params );
			req.success(
			   function(data){
					TRK.news.email.val(data).attr("disabled",true).blur();
					setTimeout(function(){
						TRK.news.email.val("").attr("disabled",false).focus();
					},2000);
				}
			);
		}
	},
	
	validity : {
		init : function() {
			var self=this;
			if( $("body").find("form").length ){
				self.addMethods();
				self.addClassRules();
			}
		},
		
		addMethods : function() {
			$.validator.addMethod(
				"placeholder",
				function(value,element){
					return this.optional(element) || value != "required"
				},
				"This field is required."
			);	
			
			$.validator.addMethod(
				"pieces",
				function(value,element){
					return value != ""
				},
				function(value,element){
					var whichForm;				
					whichForm = $(element).closest("form").find("h3").text();
					return whichForm+" needs to contain something. Click and drag pieces into it or else delete by clicking [x]"
				}
			);
		
			$.validator.addMethod(
				"expiry",
				function(value,element,params){ 
					var now,currMonth, selectedMonth, currYear;
					now = new Date();
					currYear = now.getFullYear();
					currMonth = now.getMonth();
					selectedMonth = parseInt( $(params).find(":selected").val(), 10 );
					return this.optional(element) || ! ( value <= currYear && selectedMonth < currMonth )
				},
				"credit card expired."
			);
		
			$.validator.addMethod(
				"nonZeroSelection",
				function(value,element){
					if(value == "" || value == "0") return false;
					return true; 
				},
				"please choose a dealer"
			);
		
			$.validator.addMethod(
				"commaseparated",
				function(value,element){
					//placeholder text for browsers that don't support html5 placeholder attribute coulde mistakenly be submitted.
					if(value.indexOf("name, first") >0) return false;
					//check for comma
					if(value.indexOf(",") >0) return true;
					return false;
				},
				'please use format "last name, first name."'
			);
		},
		
		addClassRules : function(){
			$.validator.addClassRules({
				cardNumber : {
					required : true,								
					creditcard : true,
					maxlength : 19,
					minlength : 13,
					placeholder : true
				},
				shipmentPieces : {
					pieces : true
				},
				expiryYear : {
					number : true,
					required : true,
					expiry : "#expiryMonth"
				},
				cardCode : {
					maxlength : 4,
					minlength : 3,
					required : true,
					placeholder : true
				},
				clientName : {
					commaseparated : true
				},
				nonZero : {
					nonZeroSelection : true
				},
				password2 : {
					equalTo : ".password"
				}
			});
		},
		
		validateForms : function(container, errorPlace){
			var self=this,forms;
			forms = $(container).find("form");
				
			forms.each(function(){
				if(errorPlace == undefined) var errorPlace = $("#quick_view");
				self.validation(this, errorPlace);
			});	
		},
		
		validation : function( frm, errorPlace ){
			var self = this, field;
			
			if(errorPlace === undefined) var errorPlace = $( "#quick_view" );
			if(errorPlace.length == 0) return false;
			$( frm ).validate ({				
				errorPlacement : function(error, element){
					BXP.pop.logPopupFormError( error, element, errorPlace, 4000, true, function(){$("#quick_view").dialog("destroy")} );
				},
				invalidHandler : function(form, validator){
					var field, message;
					field = $(form.target).data("field");
					if(field == undefined) field = "your response"; 
					message = "<br /><strong>Please check "+ field + "</strong>";
					$("#quick_view").append( message );
					$("#quick_view").dialog({
						width:"500px",
						dialogClass : "smack_dab",
						buttons : {
							"OK": function() {											
								$(this).dialog("close");
							}
						}
					});
				},
				onkeyup: false,
				onfocusout : false
			});
		},
		
		checkValidation : function( container ) {
			var self = this, forms, dfd = new $.Deferred();
			forms = $(container).find("form");
			
			forms.each(function(){
				self.validation(this);
				if( ! $(this).valid() ) { 
					dfd.reject();
					return dfd.promise();
				}
			});
			dfd.resolve();
			return dfd.promise();
		}
	}
}










/*! http://mths.be/placeholder v1.8.5 by @mathias */
;(function(window, document, $) {

	var isInputSupported = 'placeholder' in document.createElement('input'),
	    isTextareaSupported = 'placeholder' in document.createElement('textarea');

	if (isInputSupported && isTextareaSupported) {

		$.fn.placeholder = function() {
			return this;
		};

		$.fn.placeholder.input = $.fn.placeholder.textarea = true;

	} else {

		$.fn.placeholder = function() {
			return this.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
				.bind('focus.placeholder', clearPlaceholder)
				.bind('blur.placeholder', setPlaceholder)
				.trigger('blur.placeholder').end();
		};

		$.fn.placeholder.input = isInputSupported;
		$.fn.placeholder.textarea = isTextareaSupported;

		$(function() {
			// Look for forms
			$('form').bind('submit.placeholder', function() {
				// Clear the placeholder values so they don�t get submitted
				var $inputs = $('.placeholder', this).each(clearPlaceholder);
				setTimeout(function() {
					$inputs.each(setPlaceholder);
				}, 10);
			});
		});

		// Clear placeholder values upon page reload
		$(window).bind('unload.placeholder', function() {
			$('.placeholder').val('');
		});

	}

	function args(elem) {
		// Return an object of element attributes
		var newAttrs = {},
		    rinlinejQuery = /^jQuery\d+$/;
		$.each(elem.attributes, function(i, attr) {
			if (attr.specified && !rinlinejQuery.test(attr.name)) {
				newAttrs[attr.name] = attr.value;
			}
		});
		return newAttrs;
	}

	function clearPlaceholder() {
		var $input = $(this);
		if ($input.val() === $input.attr('placeholder') && $input.hasClass('placeholder')) {
			if ($input.data('placeholder-password')) {
				$input.hide().next().show().focus().attr('id', $input.removeAttr('id').data('placeholder-id'));
			} else {
				$input.val('').removeClass('placeholder');
			}
		}
	}

	function setPlaceholder() {
		var $replacement,
		    $input = $(this),
		    $origInput = $input,
		    id = this.id;
		if ($input.val() === '') {
			if ($input.is(':password')) {
				if (!$input.data('placeholder-textinput')) {
					try {
						$replacement = $input.clone().attr({ 'type': 'text' });
					} catch(e) {
						$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
					}
					$replacement
						.removeAttr('name')
						// We could just use the `.data(obj)` syntax here, but that wouldn�t work in pre-1.4.3 jQueries
						.data('placeholder-password', true)
						.data('placeholder-id', id)
						.bind('focus.placeholder', clearPlaceholder);
					$input
						.data('placeholder-textinput', $replacement)
						.data('placeholder-id', id)
						.before($replacement);
				}
				$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
			}
			$input.addClass('placeholder').val($input.attr('placeholder'));
		} else {
			$input.removeClass('placeholder');
		}
	}

}(this, document, jQuery));


/**
 * jQuery Validation Plugin 1.8.1
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 J�rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&this.find("input, button").filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name",
b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form();
else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name];
return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a,
b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",
validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)},
onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).addClass(b).removeClass(d):c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).removeClass(b).addClass(d):c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults,
a)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:c.validator.format("Please enter no more than {0} characters."),
minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator");e="on"+e.type.replace(/^validate/,
"");f.settings[e]&&f.settings[e].call(f,this[0])}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d=this.settings.rules;
c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",a).validateDelegate(":radio, :checkbox, select, option","click",a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",
[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(a){this.lastElement=a=this.clean(a);this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,
a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,function(d){return!(d.name in a)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},
objectLength:function(a){var b=0,d;for(d in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()==0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==
a.name}).length==1&&a},elements:function(){var a=this,b={};return c(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,
this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.clean(a);if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=
c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&window.console&&console.log("exception occured when checking element "+a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=
this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a]},defaultMessage:function(a,b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+
a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,element:a});this.errorMap[a.name]=d;this.submitted[a.name]=d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];
this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass)}this.toHide=this.toHide.not(this.toShow);
this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return c(this.errorList).map(function(){return this.element})},showLabel:function(a,b){var d=this.errorsFor(a);if(d.length){d.removeClass().addClass(this.settings.errorClass);d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||
"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow=this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},
idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d,e){return e.form==b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},
depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this,c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<
0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"remote")})}},classRuleSettings:{required:{required:true},
email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings,a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b=
{};a=c(a);for(var d in c.validator.methods){var e=a.attr(d);if(e)b[d]=e}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{};var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===
false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined?e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&
a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages;return a},normalizeRule:function(a){if(typeof a=="string"){var b={};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},
methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a,b)>0;default:return c.trim(a).length>0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=
e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d,mode:"abort",port:"validate"+b.name,dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=
e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||
a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(a)},
url:function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},
date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9-]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>=
0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery);
(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery);
(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a,
b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery);




//plugin allows searching designs form any input box. function passed through will have the input value as its only parameter.
$.fn.fireOnEnter = function(func){
	that = this[0];
    $(this).keypress(function(e) {
		if(e.keyCode == 13) {
		  var text = $(that).val();
	      func(text);
	    }
	});
};



