/**
  * Utiltity Library - combined javascript utilities
  * Includes: $Util, Easing v1.3, jQuery.timers
**/

//so doesn't conflict with mootools
if (typeof jQuery !== 'undefined') var $j=jQuery.noConflict();

var $Util = (function ($,$j,undefined) { 
    var my = {}, thisElem, hideId, showPopup = false, pageReturn = '', loginLnk, statusCookie = 'DPP_status';
		
	function delayHide() {
		thisElem.setStyle("display","none");	
	}
		
	function init_facebook() {
		/* facebook initialize function. Called after FB .js file loaded. Needed for facebook connect and like button */
		window.fbAsyncInit = function() {
        FB.init({appId: '111858872230821', status: true, cookie: true,
                 xfbml: true, oauth: true});
		
			//***Old way. Sets button link based on fb status.
			/*
			if(document.getElementById('fb_link'))
			{
				//Set correct button event handler depending if FB logged in or not
				FB.getLoginStatus(updateButton);
	  			//Change button event handler any time FB login status changes
				FB.Event.subscribe('auth.statusChange', updateButton);
			} */
		
  
      };	
	} 
	
	/**
	* Remove deprecated properties from jquery to avoid warnings in chrome when hovering
	* over rotator tabs
	*/
	function removeJQDeprecated() {
		var _props = $j.event.props, len = _props.length, res = [];
		for (var x=0;len--;x++) {
		  var el = _props[x];
		  if (el != 'layerX' && el != 'layerY') res.push(el);
		}
    	$j.event.props = res;
	}
	
	my.init = function() {
		init_facebook();
		my.page_ready_load();
		my.preload_images();
		if(showPopup) {$j(document).ready(function(){my.showPopAd();});}
		//remove hash tag that facebook adds on login redirect
		if (window.location.hash == '#_=_') window.location.hash = '';
		//remove jquery deprecated props
		removeJQDeprecated();
	};
	
	/* set page return variable */
	my.setReturn = function(ret) { 
		pageReturn = ret;
	};
	
	my.getReturn = function() { 
		return pageReturn;
	};
	
	/* Global page ready method. Starts when html is loaded.*/
	my.page_ready_load = function() {
		$j(document).ready(function(){
	
		//special 25th aniv promo. fade in and out mag foldout
		//anniv_mag_fade()
		//$j(document).oneTime(16000,"magfadeout",function(){anniv_mag_fade();});
		my.smooth_scroll();
		
	
		});

	};
		
    my.hide = function (elem) { 
		elem.setStyle("display","none");        

    }; 
    
	/* public method to add delay to hiding element */
	my.hideDelay = function (elem,msec) {
		thisElem = elem;
		hideID = delayHide.delay(msec);
		return hideID;
	
	};
	
	/* display element */
	my.display = function (elem) { 
		elem.setStyle("display","block");

    }; 
	
	/**
	* Set popup cookie to display popup
	*
	* If entered from home page then display on third page view.
	* If on any gallery landing page reset counter and display on secone page view.
	* All other pages display on second page view.
	* @param string isHome Home page flag
	* @param string limStart Gallery landing page flag
	* @param string view Page layout
	*/
	
	my.setPopupCookie = function(isHome,limStart,view) {
		var cooName = 'subpop';
		var cVal = {};
		var ret = false;
		//24hr flag. true = display once a day, false = follow display logic. 
		var onceADay = true;
		
		if(cooVal=my.getCookie(cooName)) {
						
			if(!onceADay) {
				
				cValObj = my.explode_to_object(cooVal,'&');
				cValObj.count = parseInt(cValObj.count);
				
				
				//Do nothing if popup already displayed
				if(cValObj.popup==='0') {
					
					cValObj.count++;
					
					//If gallery landing first page reset counter
					if(limStart==='0' && view==='images') {
						cValObj.home = '0';
						cValObj.count = 1;
					} else {
						
						if(cValObj.home=='1') {
							
							if(cValObj.count>2) {
								
								ret = true;
								cValObj.popup = '1'; 
							}
								
						} else {
							
							ret = true;
							cValObj.popup = '1'; 
						}
						
					}
						
					var newCVal = my.implode_to_string(cValObj,'&');
					//console.log('new: ' + newCVal);
					
					my.setCookie(cooName,newCVal,1); //set visited cookie value. Will expire in 24 hours.
				}
			
			}
		
		} else { 
			my.setCookie(cooName,'home=' + isHome + '&count=1&popup=0',1); //set new cookie. Will expire in 24 hours.
			//Display only once a day
			if(onceADay) ret = true;
		}
		
		showPopup = ret;
	};

	
	/* Sets cookie to expire number of days	*/
	my.setCookie = function (name,value,expDays) {
		if(name) {
			var expDate = new Date();
			var expSecs = expDate.getTime();  //Get the milliseconds since Jan 1, 1970
			expSecs += 3600*1000*24*expDays;  //add days in milliseconds
			expDate.setTime(expSecs); //Set expire date
			document.cookie = name + "=" + escape(value) + ';path=/' + ((expDays==null) ? "" : ";expires="+expDate.toUTCString());
		}
	};
	
	/* Expire cookie */
	my.expCookie = function(name) {
		document.cookie = name + '=;path=/;expires=1';					
	}
	
	/* Checks if cookie exists */
	my.getCookie = function (c_name) 	{
		//are there any cookies
		if (document.cookie.length>0)  {
		  //find specific cookie value
		  c_start=document.cookie.indexOf(c_name + "=");
		  
		  //extract cookie value
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return false;
	};
			
	my.isCookie = function (c_name) {
	
		//are there any cookies
		if (document.cookie.length>0) {
		  //get cookie value
		  c_start=document.cookie.indexOf(c_name + "=");
		  
		  //if value then cookie valid
		  if (c_start!=-1) {
				return true;
			}
		}
		return false;
	};
	
	/**
	* Will convert key=val string delimited by delim into an object
	*
	* @param string str Url query string
	* @param string delim Value delimiter
	* @return object
	*/
	
	my.explode_to_object = function(str,delim) {
		var cArr = str.split(delim);
		var cObj = new Object;
		var cLen = cArr.length;
		for(var cnt=0;cLen--;cnt++) {
			var cStr = new String(cArr[cnt]);
			var cElem = cStr.split('=');
			cObj[cElem[0]] = cElem[1];
		}
		
		return cObj;
	};
	
	/**
	* Convert Object into key=val string delimited by delim
	*
	* @param string str Url query string
	* @param string delim Delimeter
	* @return object
	*/
	
	my.implode_to_string = function(obj,delim) {
		var len = obj.length;
		var str = '';
		var elem;
		
		for(elem in obj) {
			str += delim + elem + '=' + obj[elem];	
		}
		str = str.substr(1);
		return str;
	};
	
	/* Set sign-in/out link */
	my.setLogin = function() {
		
		loginLnk = $j('#login');
		
		if(my.getCookie(statusCookie)) {//Set to Sign-Out and make sure still logged in
			my.setSignOutLink();
			my.checkLoginStatus();	
		} else {//User not logged in set to Sign-In
			my.setSignInLink();
	
		}
		
	};
	
	my.checkLoginStatus = function() {
		//Make sure user is still logged in
		$j.ajax({url: '/index.php?option=com_ajaxcomments&protocol=json&task=login.check&tmpl=component&format=raw',
				type: "POST",
				dataType: "json",
				success: my.checkLoginResp/*,
				error: my.http_error_response*/
				});
	
	};
	
	my.checkLoginResp = function(resp) {
		//If user not logged in change link to Sign-In
		if(!resp.login) {
			my.setSignInLink();
			my.expCookie(statusCookie);
		}
	};
	
	my.setSignInLink = function() {
		loginLnk.attr('href','/login.html?return=' + pageReturn);
		loginLnk.html('Sign-In');	
	}
	
	my.setSignOutLink = function() {
		loginLnk.attr('href','/logout.html?task=logout&return=' + pageReturn);
		loginLnk.html('Sign-Out');
	}
	
	
	my.check_login = function() {
	$j.ajax({url: 'index.php?option=com_ajaxcomments&protocol=json&task=login.check&tmpl=component&format=raw',
				type: "POST",
				dataType: "json",
				success: my.check_login_response/*,
				error: my.http_error_response*/
				});
	};
	
	my.check_login_response = function(resp) {
		$j(document).ready(function() {
						
			if(resp.login) 
				$j('#signin_link').attr('href','/logout.html').html('Sign-Out');
			else
				$j('#signin_link').attr('href','/index.php?option=com_user&view=login&return=' + $Util.page_return).html('Sign-In');
				
			});
				
	};

	my.http_error_response = function(xhr,status) {
		alert('Error Encountered: HTTP ' + xhr.status + ' ' + xhr.statusText);	
	};
	
	/* Display popup ad */
	my.showPopAd = function() {
			
		var _popForm = $('popad');
		
		if(_popForm) {
			//add click event for popup form. will cancel closing if popup clicked
			_popForm.addEvent('click',function() {clearTimeout(hideId);});
		
			my.display(_popForm);
			
			//delay closing of popup
			hideId = my.hideDelay(_popForm,15000);
		}
		
	};

	my.closePopAd = function () {
		my.hide($('popad'));
	};
	
	my.paging_img_switch = function(img,dir,flag) {
		
		if(flag=="over") {
			img.src = "/templates/dpp/images/" + dir + "-active.png";
		} else {
			img.src = "/templates/dpp/images/" + dir + "-inactive.png";
		}
		
	};
	
	my.smooth_scroll = function () {
		   if ($j !== undefined) {
			   $j('.scrollTop').click(function() {
				
				   //var newHash='#top';
				   var target=jQuery('body').offset().top,
				   duration=800,
				   easing='easeOutQuint';
				   // animate to target
				   $j('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing);
				   //Cancel click event
				
					return false;
	
				});
		   }
			   
	};
	
	my.preload_images = function() {
		img1 = new Image(9,13);
		img2 = new Image(9,13);
		img3 = new Image(9,13);
		img4 = new Image(9,13);
		img1.src = "/templates/dpp/images/next-active.png";
		img2.src = "/templates/dpp/images/prev-active.png";
		img3.src = "/templates/dpp/images/next-inactive.png";
		img4.src = "/templates/dpp/images/prev-inactive.png";

	};
	
	my.edit_box = function(lightbox) {
		//make sure Jquery loaded
		if(typeof $j != 'undefined')
		{
			$j('#lightbox_title').val($j('#title_' + lightbox).html());
			$j('#lightbox_id').val(lightbox);
			$j('#subbut').html('Update');
			$j('#l_title').html('Update Lightbox');
			$j('#task').val('lightbox.update');
		}
	
	};
	
	my.submitContact = function(frm) {
		
		var valid = document.formvalidator.isValid(frm);
		
		if(valid===true) {
			$('load-spin').setStyle('visibility','visible');
			$('emailForm').send({onComplete: function(data) {
				$('load-spin').setStyle('visibility','hidden');
				alert('Your message has been submitted.');
				window.parent.document.getElementById('sbox-window').close();				
			}});
		}
		return false; 		
	};
	
	//base 64 decode	
	var b64array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	my.decode64 = function(input) {
		var output = "", hex = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "",i = 0,len=input.length;
		do {
			enc1 = b64array.indexOf(input.charAt(i++));enc2 = b64array.indexOf(input.charAt(i++));enc3 = b64array.indexOf(input.charAt(i++));enc4 = b64array.indexOf(input.charAt(i++));chr1 = (enc1 << 2) | (enc2 >> 4);chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);chr3 = ((enc3 & 3) << 6) | enc4;output = output + String.fromCharCode(chr1);if (enc3 != 64) {output = output + String.fromCharCode(chr2);}if (enc4 != 64) {output = output + String.fromCharCode(chr3);}chr1 = chr2 = chr3 = enc1 = enc2 = enc3 = enc4 = "";} while (i < len);
		return output;
	};
	
    return my; 
  
}($,jQuery));


/* ******** Page Functions ************ */

function officialRules(url) {
	a = window.open(url,'rules','width=650,height=525,resizable=no,scrollbars=yes,toolbar=no,directories=no,status=no');
	var width = 650; 
	var height = 525;
	var aw = screen.availWidth; 
	var ah = screen.availHeight; 
	var xPos = (aw - width)/2; 
	var yPos = (ah - height)/2; 
	a.moveTo(xPos,yPos);
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function grabvar( name ) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
	return "";
	else
	return results[1];
}


/* ********* Jquery Extensions go here ********** */

if (typeof jQuery != 'undefined') {
	/*
	 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
	 *
	 * Uses the built in easing capabilities added In jQuery 1.1
	 * to offer multiple easing options
	 */
	
	// t: current time, b: begInnIng value, c: change In value, d: duration
	jQuery.easing['jswing'] = jQuery.easing['swing'];
	
	jQuery.extend( jQuery.easing,
	{
		def: 'easeOutQuad',
		swing: function (x, t, b, c, d) {
			//alert(jQuery.easing.default);
			return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
		},
		easeInQuad: function (x, t, b, c, d) {
			return c*(t/=d)*t + b;
		},
		easeOutQuad: function (x, t, b, c, d) {
			return -c *(t/=d)*(t-2) + b;
		},
		easeInOutQuad: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t + b;
			return -c/2 * ((--t)*(t-2) - 1) + b;
		},
		easeInCubic: function (x, t, b, c, d) {
			return c*(t/=d)*t*t + b;
		},
		easeOutCubic: function (x, t, b, c, d) {
			return c*((t=t/d-1)*t*t + 1) + b;
		},
		easeInOutCubic: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t*t + b;
			return c/2*((t-=2)*t*t + 2) + b;
		},
		easeInQuart: function (x, t, b, c, d) {
			return c*(t/=d)*t*t*t + b;
		},
		easeOutQuart: function (x, t, b, c, d) {
			return -c * ((t=t/d-1)*t*t*t - 1) + b;
		},
		easeInOutQuart: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
			return -c/2 * ((t-=2)*t*t*t - 2) + b;
		},
		easeInQuint: function (x, t, b, c, d) {
			return c*(t/=d)*t*t*t*t + b;
		},
		easeOutQuint: function (x, t, b, c, d) {
			return c*((t=t/d-1)*t*t*t*t + 1) + b;
		},
		easeInOutQuint: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
			return c/2*((t-=2)*t*t*t*t + 2) + b;
		},
		easeInSine: function (x, t, b, c, d) {
			return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
		},
		easeOutSine: function (x, t, b, c, d) {
			return c * Math.sin(t/d * (Math.PI/2)) + b;
		},
		easeInOutSine: function (x, t, b, c, d) {
			return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
		},
		easeInExpo: function (x, t, b, c, d) {
			return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
		},
		easeOutExpo: function (x, t, b, c, d) {
			return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
		},
		easeInOutExpo: function (x, t, b, c, d) {
			if (t==0) return b;
			if (t==d) return b+c;
			if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
			return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
		},
		easeInCirc: function (x, t, b, c, d) {
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
		},
		easeOutCirc: function (x, t, b, c, d) {
			return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
		},
		easeInOutCirc: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
			return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
		},
		easeInElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		},
		easeOutElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
		},
		easeInOutElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
			return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
		},
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		},
		easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
		},
		easeInOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158; 
			if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
			return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
		},
		easeInBounce: function (x, t, b, c, d) {
			return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
		},
		easeOutBounce: function (x, t, b, c, d) {
			if ((t/=d) < (1/2.75)) {
				return c*(7.5625*t*t) + b;
			} else if (t < (2/2.75)) {
				return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
			} else if (t < (2.5/2.75)) {
				return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
			} else {
				return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
			}
		},
		easeInOutBounce: function (x, t, b, c, d) {
			if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
			return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
		}
	});
	
	
	/**
	 * jQuery.timers - Timer abstractions for jQuery
	 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
	 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
	 * Date: 2009/10/16
	 *
	 * @author Blair Mitchelmore
	 * @version 1.2
	 *
	 **/
	
	jQuery.fn.extend({
		everyTime: function(interval, label, fn, times) {
			return this.each(function() {
				jQuery.timer.add(this, interval, label, fn, times);
			});
		},
		oneTime: function(interval, label, fn) {
			return this.each(function() {
				jQuery.timer.add(this, interval, label, fn, 1);
			});
		},
		stopTime: function(label, fn) {
			return this.each(function() {
				jQuery.timer.remove(this, label, fn);
			});
		}
	});
	
	jQuery.extend({
		timer: {
			global: [],
			guid: 1,
			dataKey: "jQuery.timer",
			regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
			powers: {
				// Yeah this is major overkill...
				'ms': 1,
				'cs': 10,
				'ds': 100,
				's': 1000,
				'das': 10000,
				'hs': 100000,
				'ks': 1000000
			},
			timeParse: function(value) {
				if (value == undefined || value == null)
					return null;
				var result = this.regex.exec(jQuery.trim(value.toString()));
				if (result[2]) {
					var num = parseFloat(result[1]);
					var mult = this.powers[result[2]] || 1;
					return num * mult;
				} else {
					return value;
				}
			},
			add: function(element, interval, label, fn, times) {
				var counter = 0;
				
				if (jQuery.isFunction(label)) {
					if (!times) 
						times = fn;
					fn = label;
					label = interval;
				}
				
				interval = jQuery.timer.timeParse(interval);
	
				if (typeof interval != 'number' || isNaN(interval) || interval < 0)
					return;
	
				if (typeof times != 'number' || isNaN(times) || times < 0) 
					times = 0;
				
				times = times || 0;
				
				var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
				
				if (!timers[label])
					timers[label] = {};
				
				fn.timerID = fn.timerID || this.guid++;
				
				var handler = function() {
					if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
						jQuery.timer.remove(element, label, fn);
				};
				
				handler.timerID = fn.timerID;
				
				if (!timers[label][fn.timerID])
					timers[label][fn.timerID] = window.setInterval(handler,interval);
				
				this.global.push( element );
				
			},
			remove: function(element, label, fn) {
				var timers = jQuery.data(element, this.dataKey), ret;
				
				if ( timers ) {
					
					if (!label) {
						for ( label in timers )
							this.remove(element, label, fn);
					} else if ( timers[label] ) {
						if ( fn ) {
							if ( fn.timerID ) {
								window.clearInterval(timers[label][fn.timerID]);
								delete timers[label][fn.timerID];
							}
						} else {
							for ( var fn in timers[label] ) {
								window.clearInterval(timers[label][fn]);
								delete timers[label][fn];
							}
						}
						
						for ( ret in timers[label] ) break;
						if ( !ret ) {
							ret = null;
							delete timers[label];
						}
					}
					
					for ( ret in timers ) break;
					if ( !ret ) 
						jQuery.removeData(element, this.dataKey);
				}
			}
		}
	});
	
	jQuery(window).bind("unload", function() {
		jQuery.each(jQuery.timer.global, function(index, item) {
			jQuery.timer.remove(item);
		});
	});
	
}
