/*
 * generic jQuery form validation extensions and messages
 */

if (!window.pictage) window.pictage = {};
pictage.submitInProgress = {};
pictage.env = {};
pictage.regex = {
		fullDate: /\d{2}\/\d{2}\/\d{4}/,
		stdYear: /\d{4}/
};

pictage.AJAX_TIMEOUT = 25000; // 25 seconds

window.genericErrorMsgs = {
	noSpecialChars: "Please use only letters, number, spaces and the following special characters - , & ' / : ; .",
	textMax: "40 character limit.",
	multiEmailSingular: " is not a valid email address.",
	multiEmailPlural: " are not valid email addresses.",
	noFirst: "Please enter a first name.",
	noLast: "Please enter a last name.",
	noEventSelected: "Please select an event.",
	nonStdYear: "Please ensure that the date has a four digit year.",
	staleDate: "Please enter a future date."
};

if (window.jQuery) {
	// re: prevent double form submits
	$('form').submit(function(){
		var self = $(this);
		var action = self.attr('action');
		if (pictage.submitInProgress[action]) {
			return false;
		}
		else {
			pictage.submitInProgress[action] = true;
		}
	});
	
	pictage.globalAjaxError = function(xhr, status, error){
		if (xhr.responseText.indexOf("Login") != -1 || xhr.responseText.indexOf("j_spring_security_check") != -1 || xhr.responseText.indexOf("secure.pdisp.pictage.com") != -1) {
			window.location.reload(true);
			return;
		}
		if(xhr.responseText.indexOf("<title>..:: Pictage | Technical Error ::..</title>") !=-1) {
			document.write(xhr.responseText);
			document.close();
			return;
		}
		var proc = $('#processing');
		if (proc.length > 0) {
			var timer = setTimeout(function(){proc.hide();}, 800);
		}
		if (pictage.imageTray) {pictage.imageTray.busy = false;}
		if(String(window.location).indexOf("layout=mobile") == -1) {popupManager.show({id: 'popup-error-msg', error: true, coverpage: true, inject: {".popup-error-text": 'A network error occurred. Please try again later.'}});}
	};
	
	// global AJAX settings
	$.ajaxSetup({
		timeout: pictage.AJAX_TIMEOUT,
		beforeSend: function() {// re: prevent double form submits
			if (this.type === "POST") {
				pictage.submitInProgress[this.url] = true;
			}
		},
		error: pictage.globalAjaxError,
		complete: function(xhr, status) {// re: prevent double form submits
			var url = this.url;
			if (pictage.submitInProgress[url]) {
				pictage.submitInProgress[url] = false;
			}
		},
		traditional: true
	});
	
	
	$(function(){
		// target blank fixes
		$('.tblank').attr('target', '_blank');
		$('.ptarget').each(function(){
			var self = $(this);
			self.attr('target', self.children('.targetname').html());
		});
		// disable default link action on any "naked" hash links
		$('a[href=#]').click(function(e){
			e.preventDefault();
		});
	});
}

if (window.jQuery && jQuery.validator) {
	jQuery.validator.setDefaults({
		onfocusout: false,
		errorClass: "simple-error"
	});
	
	jQuery.validator.addMethod("isStdYear", function(value, elem){
		var val = value.substring(value.lastIndexOf("/")+1, value.length);
		return pictage.regex.stdYear.test(val) && val.length == 4;
	}, genericErrorMsgs.nonStdYear);
	
	jQuery.validator.addMethod("isFutureDate", function(value, elem){
		return new Date(value) > new Date();
	}, genericErrorMsgs.staleDate);
	
	jQuery.validator.addMethod("validEventSelected", function(value, elem){
		if (value == 0 || value === "" || value.toLowerCase() === "no matching events") {
			return false;
		}
		return true;
	}, genericErrorMsgs.noEventSelected);
	
	jQuery.validator.addMethod("noSpecialChars", function(value, elem){
		var specialChar = /\W|"|_/gi;
		var accept = /[-,&'\/:;\s\.]/;
		var test = value.match(specialChar);
		if (test) {
			for (var i=0; i < test.length; i++) {
				if (!test[i].match(accept)) return false;
			}
		}
		return true;
		
	}, genericErrorMsgs.noSpecialChars);
	
	jQuery.validator.addMethod("noFirst", function(value, elem){
		if (value.toLowerCase() == "first") return false;
		return true;
		
	}, genericErrorMsgs.noFirst);
	
	jQuery.validator.addMethod("noLast", function(value, elem){
		if (value.toLowerCase() == "last") return false;
		return true;
		
	}, genericErrorMsgs.noLast);
	
	jQuery.validator.addMethod("multiEmail", function(value, elem) {
		if( null == value || "" == value ) return true;
		var emails = value.replace(/^\s+|\s+$/g,"").replace(/[\r\n\t; ,]+/g, ",").split(",");
		
		pictage.clientEmailErrors = [];
		var re = /^((([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;
		for (var i=0; i < emails.length; i++) {
			var val = jQuery.trim(emails[i]);
			if (!re.test(val)) {
				pictage.clientEmailErrors .push(val);
			}
		}
		
		if (pictage.clientEmailErrors .length > 0) {
			return false;
		}
		return true;
		
	}, function() {
		var msg = pictage.clientEmailErrors.length == 1 ? genericErrorMsgs.multiEmailSingular : genericErrorMsgs.multiEmailPlural;
		return (pictage.clientEmailErrors + msg);
	});
}

pictage.STD_INPUT_LEN = 40;

pictage.getRandId = function() {
	return (new Date().getTime());
};

pictage.loadCss = function(url) {
	var css = document.createElement("link");
	css.setAttribute("rel", "stylesheet");
	css.setAttribute("type", "text/css");
	css.setAttribute("href", url);
	document.getElementsByTagName("head")[0].appendChild(css);
};

pictage.getCookie = function(Name) {
    var aCookie = document.cookie.split("; ");

    for ( var i=0 ; i < aCookie.length ; i++ )
    {
        var aCval = aCookie[i].split("=");
        if ( ( Name == aCval[0]) && ( aCval.length > 1 ) ) return unescape( aCval[1] ) ;
    }

    return false ;
};


pictage.setCookie = function (Name,Value,Expires) {
    var pvalue   = escape(Value) ;
    var pExpires = Expires ;

    var pPath    = ';Path=/' ;

    // Get subdomain if more than one "." in the host name
    var pDomain  = document.URL;
    pDomain = pDomain.substring( pDomain.indexOf( '//' ) + 2 );
    idx = pDomain.indexOf( ':' );
    if ( idx >= 0 )
        pDomain = pDomain.substring( 0, idx );
    idx = pDomain.indexOf( '/' );
    if ( idx >= 0 )
        pDomain = pDomain.substring( 0, idx );
    idx = pDomain.indexOf( '.' );
    if ( idx != pDomain.lastIndexOf( '.' ) )
        pDomain = ';domain=' + pDomain.substring( idx );
    else
        pDomain = '';
    
    pExpires = pExpires == "never" ? 'Fri, 31 Dec 2099 23:59:59 GMT;' : (pExpires || '');
    document.cookie = (Name + '=' + pvalue + ';expires=' + pExpires + pPath + pDomain);
};

/* Animated Rotator - for fading through series of images (or whatever else) in a gallery
pictage.animatedRotator = function (interval,container){
	if ($(container).children().length > 1) {
		setInterval(function(){
			var active = $(container +' > .animRotatorActive');
			var next = (active.next('li'))? active.next('li') : $(container).children('li:first');
			active.siblings().css('visibility','hidden');
			next.css('visibility','visible');
			active.fadeOut(1000, function() {
				active.removeClass('animRotatorActive').css('display','block');
				next.addClass('animRotatorActive');
			});
		},interval);
	}
};*/


pictage.animatedRotator = function (interval,container){
	// checks whether there is more than one slide before running animation
	if ($(container).children().length > 1) {
		//randomizes first slide if ".animRotatorActive" class hasn't been given to one of them
		if ($(container).find('.animRotatorActive').length < 1) {
      $(container).children('li:first').addClass('animRotatorActive');
		}
		setInterval(function(){
			var active = $(container +' > .animRotatorActive');
			var next = active.nextAll('li:first')[0] ? active.nextAll('li:first') : $(container).children('li:first');
			active.siblings().css('visibility','hidden');
			next.css('visibility','visible');
			active.fadeOut(1000, function() {
				active.removeClass('animRotatorActive').css('display','block');
				next.addClass('animRotatorActive');
			});
		},interval);
	}
};




// Simple Accordion
function simpleAccordion (activator,firstOpen,limitOne) {
	$(activator).click(function() {
		$(this).toggleClass('closed').next().toggle(500);
		// if this is true, only one item will be permitted to be open at a time
		if (limitOne === true) {
			$(activator).not($(this)).addClass('closed').next().hide(500);
		}
		return false;
	});
	// if firstOpen is true, the first item will be open on load
	if (firstOpen === true) {
		$(activator).filter(':not(:first)').addClass('closed').next().hide();
	// if firstOpen is an integer, then it will select an item by index (1-based) to be open on load
	} else if (firstOpen === parseInt(firstOpen)) {
		$(activator+':not(:eq('+(firstOpen-1)+'))').addClass('closed').next().hide();
	// if there is a hash (#) in the url, tests to see if it points to one of the activators, and opens that activator if it is
	// then tests to see whether the url hash points to an ID inside one of the accordion content areas, and opens that one if it does
	} else if (window.location.hash) {
		var activatorHasId = 0;
		$(activator).each(function(){
			if (('#'+$(this).attr('id')) === window.location.hash){
				$(activator).not($(window.location.hash)).addClass('closed').next().hide();
				activatorHasId = 1;
				return;
			}
		});
		if (activatorHasId != 1){
			$(activator).not($(window.location.hash).parents().prev(activator)).addClass('closed').next().hide();
		}
	// otherwise firstOpen will be accepted as a css selector for the item (or items) to be open on load, and where none are present, all items will be closed on load
	} else {
		$(activator+':not('+firstOpen+')').addClass('closed').next().hide();
	}
}

// Expiration Date
function expirationDate (el,year,month,day) {
	var expirationDate = new Date();
	expirationDate.setFullYear(year,(month-1),day);
	var currentDate = new Date();
	if(expirationDate<currentDate){
		$(el).hide();
	}
}

function getUrlParams() {
	   var urlParams = {};
	                
	   var e,
	        a = /\+/g,  // Regex for replacing addition symbol with a space
	        r = /([^&=]+)=?([^&]*)/g,
	        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
	        q = window.location.search.substring(1);

	    while (e = r.exec(q)) {
	       urlParams[d(e[1])] = d(e[2]);
	                }
	                
	                 return urlParams
	};

// from the jQuery.client plugin by stoimen

(function() {
	
	var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.userAgent,
				subString: "iPhone",
				identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	
	};
	
	BrowserDetect.init();
	
	window.$.client = { os : BrowserDetect.OS, browser : BrowserDetect.browser };
	
	switch($.client.os) {
		case "Mac":
			pictage.env.ctrlClick = "altKey";
			pictage.env.ctrlDisplay = "Alt/Option";
			$('#mac-option').show();
			break;
		case "Windows":
			pictage.env.ctrlClick = "ctrlKey";
			pictage.env.ctrlDisplay = "Ctrl";
			$('#win-ctrl').show();
			break;
		default:
			pictage.env.ctrlClick = "ctrlKey";
			pictage.env.ctrlDisplay = "Ctrl";
			$('#win-ctrl').show();
	}
	
})();




// Deprecated. To be removed. - JG 08/17/2009
// Toggle Popup Divs
function toggleLayer( popupname )
{
	var elem, vis;
	if( document.getElementById ) // this is the way the standards work
	elem = document.getElementById( popupname );
	else if( document.all ) // this is the way old msie versions work
	  elem = document.all[popupname];
	else if( document.layers ) // this is the way nn4 works
	elem = document.layers[popupname];
	vis = elem.style;
	// if the style.display value is blank we try to figure it out here
	if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
	vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
	vis.display = (vis.display==''||vis.display=='block')?'none':'block';
	window.scrollTo(0,0);
}

