(function($) {
	$.fn.jSlide = function(options) {
		var opts = $.extend({}, $.fn.jSlide.defaults, options);
		
		var target = $(this);
		
		var setupGallery = function(){
			var numphotos = document.getElementById('ez_total_photos');
			if(numphotos.value != "")
			{
				opts.maxi = numphotos.value;
			}
			else
			{
				opts.maxi = target.find("div").length;
			}
			target.wrap('<div class="jSlide"></div>');
			resize();
			$(window).resize(resize);
			
			var PrevButton;
			if(opts.buttonScope)
				PrevButton = $(opts.buttonScope).find(".jSlidePrev");
			else
				PrevButton = $(".jSlidePrev");
				
			PrevButton.click(function(){
				if (opts.cur > 0)
					opts.cur--;
				else
					opts.cur = opts.maxi -1;

				target.animate({
					marginLeft: "-" + (opts.cur * target.find(":first-child").width() + "px")
				}, opts.duration);
				
				changeCurrentSideText();
				
				doClickEvents();
				
			});
			
			var NextButton;
			if(opts.buttonScope)
				NextButton = $(opts.buttonScope).find(".jSlideNext");
			else
				NextButton = $(".jSlideNext");
				
			
			NextButton.click(function(){
				if (opts.cur < opts.maxi - 1)
					opts.cur++;
				else
					opts.cur = 0;

				target.animate({
					marginLeft: "-" + (opts.cur * target.find(":first-child").width() + "px")
				}, opts.duration);
				
				changeCurrentSideText();
				
				doClickEvents();
				
			});
			
			
			
			changeCurrentSideText();
			changeTotalSideText();
			
		};
		
		var doClickEvents = function()
		{
			if(opts.onClickEvent)
			{
				opts.onClickEvent(opts);
			}
		}
		
		var changeCurrentSideText = function()
		{
			if(opts.currentSideTextScope)
			{
				$(opts.currentSideTextScope).html(opts.cur + 1 );
			}
		};
		
		var changeTotalSideText = function()
		{
			if(opts.totalSideTextScope)
			{
				$(opts.totalSideTextScope).html(opts.maxi);
			}
		};
		
		var resize = function (x){
			/* potential issues: 
				Legacy Browsers: test old browsers
				Image Sizes: need to define rules ( prob explictly use the first image as height and width for entire gallery, now its implicit)
				Performance and user experiance: make smaller calls for load images via ajax (now it loads the entire gallery).  */
			target.parent('.jSlide').css({
				position:"relative",
				width: opts.width,
				overflow: "hidden"
			});
		
			target.css({
				position:"relative",
				width: target.parent('.jSlide').width()*target.children().length+"px",
				overflow: "hidden"
			});
		
			target.children().css({
				position:"relative",
				width: target.parent('.jSlide').width()+"px",
				"float":"left"
			});
			
			target.css({
				marginLeft: "-" + (opts.cur * target.find(":first-child").width() + "px")
			});
		};
		
		var setupRemoteGallery = function(){
			target.load(opts.galleryContentUrl, setupGallery);
		};
		
		if(opts.galleryContentUrl || (opts.useInElementRemoteUrl && opts.useInElementRemoteUrl =='true' ) )
		{
			if(opts.useInElementRemoteUrl && opts.useInElementRemoteUrl =='true' )
				opts.galleryContentUrl = target.attr('rel');
				
			setupRemoteGallery();
		}
		else
			setupGallery();
	
		return target;
	};
	
	$.fn.jSlide.defaults = {
		easing: "swing",
		duration: 300,
		width: "100%",
		buttonScope: false,
		galleryContentUrl: false,
		currentSideTextScope: false,
		totalSideTextScope: false,
		useInElementRemoteUrl: false,
		onClickEvent: false,
		cur: 0,
		maxi: 0
	};
	
})(jQuery);


var utils = new Object();
utils.getcookie = function(NameOfCookie) 
{
	if (document.cookie.length > 0)	
	{begin = document.cookie.indexOf(NameOfCookie+"=");
	if (begin != -1)
	{begin += NameOfCookie.length+1;
	end = document.cookie.indexOf(";", begin);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(begin, end)); }
	}
	return null;
}	

utils.setcookie = function(c_name,value,path,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	( ( path ) ? ";path=" + path : "") +
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
	
utils.deletecookie = function( name, path, domain ) 
{
	if ( this.getcookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

utils.querystring = function (qval) 
{
	var qsParm = new Array();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
			if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
			}
	}
	if (qsParm[qval]){
		return decodeURIComponent(qsParm[qval]);
	}
	else{
		return "";
	}
}	

utils.formToMap = function(formname)
{
	if( jQuery(formname).is('form') )
	{
		var obj = new Object();
		var testarray = jQuery(formname).find('input');

		for(i=0;i<testarray.length;i++)
		{
		    if( jQuery(testarray[i]).attr('value') != '' && jQuery(testarray[i]).attr('type') == 'hidden')
		    {
		         eval('obj.' +jQuery(testarray[i]).attr('name') +'='+  jQuery(testarray[i]).attr('value')   );   
		    }
		}
		return obj;
	}
}

utils.formToQueryString = function(formQuery)
{
    return jQuery(formQuery).attr('action') + '?'+ jQuery(formQuery).find('input').serialize();
}

var ads = new Object();
ads.registered = new Array();

ads.getval = function (key)
{
	if( document.getElementById(key) )
		return document.getElementById(key).value;
	else
		return NULL;
}
		
ads.createadframe = function (iframeWidth, iframeHeight, url)
{
	var frame_loc = "staticfiles/ads/ad_iframe.html";
	var ad_link  = frame_loc + '@url=' + encodeURIComponent(url);			
	return '<iframe class="iframead" src="' +ad_link + '" scrollbar="no" scrolling="no" frameborder="0" height="' + iframeHeight + '" width="' + iframeWidth + '"><\/iframe>';
}
			
ads.registeradcall = function(urlval, nameval, sizeval)
{
	this.registered.push({url:urlval, name:nameval, size:sizeval});
}
		
ads.refreshIframes = function()
{
	jQuery('iframe.iframead').each( function() {
		jQuery(this).attr('src', jQuery(this).attr('src') );
	});
}	

ads.builddebugui = function()
{
	var output = '';
	
	for(i=0;i<this.registered.length;i++) {
		output += ("<li>call:" +(i + 1)+ " url:" +this.registered[i].url + "</li>");
	}
	
	if( output != '')
		output = '<ol>' + output + '</ol>';
	else
		output = '<p>there are no ads registered on this page.</p>';
	
	var cookieval = utils.getcookie('addebug');
	var buttontext = 'turn on auto pop';
	
	if(cookieval && cookieval == 'auto')
		 buttontext = 'turn off auto pop';
	
	var button = '<a href="#" title="toggle the auto debug popup" class="adbutton toggleaddebug">' +buttontext+ '</a>';
	
	var finaloutput = jQuery('<div class="addebug"><div class="debugheader"><b>Ads Debug Console:</b> ' +button+ '</div>' +output+ '</div>');
	
	finaloutput.find('.toggleaddebug')
		.click( function() { 
			var cookieval = utils.getcookie('addebug');
			
			if(cookieval && cookieval == 'auto'){
				utils.setcookie('addebug','off', './');
				jQuery(this).html('turn on auto pop');
			}
			else{
				utils.setcookie('addebug','auto', './');
				jQuery(this).html('turn off auto pop');
			}
								
			return false;
				
		});
	
	jQuery('body').prepend(finaloutput);
	
}

ads.debugstart = function()
{
	if(utils.querystring('debugads') == 'true' || utils.getcookie('addebug') =='auto')
	{
		this.builddebugui();
	}
}
