﻿var urlHandler={
	addQueryKeyValue: function(url,queryKey,value) {
		var urlWithoutHash=urlHandler.stripHash(url),
					hash=urlHandler.getHash(url);
		return urlWithoutHash+(urlWithoutHash.indexOf("?")> -1?"&":"?")+queryKey+"="+encodeURIComponent(value)+(hash===null?"":"#"+hash);
	},
	removeQueryKey: function(url,queryKey) {
		var m=new RegExp("(\\?|&)("+queryKey+"=.*?)($|&|#)").exec(url);
		return m===null?url:url.replace(m[1]+m[2]+m[3],m[1]=="?"&&m[3]!==""?m[1]:m[3]);
	},
	hasQueryKey: function(url,queryKey) {
		return url.indexOf("&"+queryKey+"=")> -1||url.indexOf("?"+queryKey+"=")> -1;
	},
	getValueForQueryKey: function(url,queryKey) {
		var m=new RegExp("(\\?|&)"+queryKey+"=(.*?)($|&|#)").exec(url);
		return m===null?null:decodeURIComponent(m[2]).replace(/[\+]/g," ");
	},
	getValueForQueryKeyInHash: function(url,queryKey) {
		var m=new RegExp("[#](.*?&){0,1}?"+queryKey+"=(.*?)($|&)").exec(url);
		return m===null?null:decodeURIComponent(m[2]).replace(/[\+]/g," ");
	},
	replaceOrAddQueryKeyAndValue: function(url,queryKey,value) {
		var queryValue=urlHandler.getValueForQueryKey(url,queryKey),
					newUrl,
					urlWithoutHash,
					hash;
		if(queryValue==value) {
			return url;
		}
		newUrl=url.replace(new RegExp("(\\?|&)("+queryKey+"=)(.*?)($|&|#)"),"$1$2"+encodeURIComponent(value)+"$4");
		if(url==newUrl) {
			urlWithoutHash=urlHandler.stripHash(url);
			hash=urlHandler.getHash(url);
			newUrl=urlWithoutHash+(urlWithoutHash.indexOf("?")> -1?"&":"?")+queryKey+"="+encodeURIComponent(value)+(hash===null?"":"#"+hash);
		}
		return newUrl;
	},
	stripQuery: function(url) {
		var hash=urlHandler.getHash(url);
		return url.indexOf("?")> -1?url.substring(0,url.indexOf("?"))+(hash===null?"":"#"+hash):url;
	},
	stripHash: function(url) {
		return url.indexOf("#")> -1?url.substring(0,url.indexOf("#")):url;
	},
	getHash: function(url) {
		var m=/#(.*?)$/.exec(url);
		return m===null?null:m[1];
	}
}



function InitSlide(speed){
	$(document).ready(function() {
		$(".slide").handleSlide(speed);
		
		$('.slide .pauseResume').click(function() {
			if($(".slide").hasClass('playing')){
				$(".slide .slides").cycle('pause');
				$(".slide").removeClass('playing');
				$(".slide").addClass('paused');
			} else {
				$(".slide .slides").cycle('resume');
				$(".slide").addClass('playing');
				$(".slide").removeClass('paused');
			}
			return false;
		});
		
		$('.slide .next-page').click(function() {
			if($(".slide").hasClass('playing')){
				$(".slide .slides").cycle('pause');		
				$(".slide").removeClass('playing');
				$(".slide").addClass('paused');
			}
			return false;
		});		
		$('.slide .previous-page').click(function() {
			if($(".slide").hasClass('playing')){
				$(".slide .slides").cycle('pause');		
				$(".slide").removeClass('playing');
				$(".slide").addClass('paused');				
			}
			return false;
		});				
	});
}

jQuery.fn.handleSlide=function(speed, callBack) {
	if(this.size()>0) {
		this.each(function() {
			var con=$(this),
					slides=con.find(".slides"),
					paging=slides.next(".slide-paging"),
					slideId,
					number,
					url,
					cityArea,
					img;
			if(paging.size()!==0) {
				slideId=con.attr("id");
				number=slideId.substring(slideId.indexOf("_")+1);
				url=urlHandler.addQueryKeyValue(urlHandler.addQueryKeyValue(urlHandler.stripHash(document.location.href),"json",""),"slideshow"+number,"");
				$.getJSON(url,function(data) {
					function getImageIndexFromElmId(id) {
						return id.slice(id.lastIndexOf("_")+1,id.length);
					}
						var j,
							initialSlide=slides.find("p:first"),
							slideSelector=" #"+slideId,
							currentImage=con.find(".index .currentPage"),
							startSlide=currentImage.size()===0?1:parseInt(currentImage.text(),10),
							imagePrefix=slideId+"_",
							imgArray=[],
							i,
							k;
					initialSlide
							.attr("id",imagePrefix+startSlide)
							.find("img")
								.addClass("has-paging");
					con.addClass("slide-done");
					if(jQuery.isFunction(callBack)) {
						callBack.call();
					}
					function createImageObject(item,index) {
						/* Create paragraph */
						var p=$(document.createElement("p"))
								.css("opacity","0")
								.attr("id",imagePrefix+index);
						p.addClass("position"+item.Position);
						/*Create author wrapper*/
						if(item.Author!==null&&item.Author!=="") {
							authorWrapper = $(document.createElement("span"));
							authorWrapper.addClass("authorWrapper");
							author = $(document.createElement("span"));
							author.addClass("author");
							author.html(item.Author);
							author.prependTo(authorWrapper);
							authorWrapper.prependTo(p);
						}
						/*Create Intro/Description wrapper*/
						var descriptionWrapper;
						if(item.DescriptionLink!==null&&item.DescriptionLink!=="") {
							descriptionWrapper = $(document.createElement("a"));
							descriptionWrapper.addClass("panel-link");
							descriptionWrapper.attr("href",item.DescriptionLink);
						} else {
							descriptionWrapper = $(document.createElement("span"));
						}
						descriptionWrapper.addClass("description-wrapper");
						var imgHeight = slides.height();
						var imgWidth = slides.width();
						if(item.NarrowTextPanel) {
							descriptionWrapper.addClass("narrow-text-panel");
						}
						if(item.Position == 2) {
							if($(".slide div").hasClass('large-slide')) {
								descriptionWrapperHeightOffset = 50/2;
								if(item.NarrowTextPanel) {
									descriptionWrapperWidthOffset = 200/2;
								} else {
									descriptionWrapperWidthOffset = 400/2;
								}
							} else {
								descriptionWrapperHeightOffset = 40/2;
								if(item.NarrowTextPanel) {
									descriptionWrapperWidthOffset = 100/2;
								} else {
									descriptionWrapperWidthOffset = 200/2;									
								}								
							}
							descriptionWrapper.css({"bottom" : (imgHeight/2)-descriptionWrapperHeightOffset+"px", "right" : (imgWidth/2)-descriptionWrapperWidthOffset+"px"});
						}
						var innerDescriptionWrapper = $(document.createElement("span"));
						innerDescriptionWrapper.addClass("inner-description-wrapper");
						if(item.AlignTextRight) {
							innerDescriptionWrapper.addClass("align-text-right");
						}
						innerDescriptionWrapper.prependTo(descriptionWrapper);
						/* Create Description*/
						if(item.Description!==null&&item.Description!=="") {
							/* Create span */
							var span = $(document.createElement("span")).html(item.Description);
							span.addClass("slide-description-label");
							span.prependTo(innerDescriptionWrapper);							
							}
						/*Create Intro*/
						if(item.Intro!==null&&item.Intro!=="") {
							/* Create span */
							var span = $(document.createElement("span")).html(item.Intro);
							span.addClass("slide-intro-label");
							span.prependTo(innerDescriptionWrapper);
						}					
						if((item.Description!==null && item.Description!=="") || (item.Intro!==null && item.Intro!=="")) {
							descriptionWrapper.prependTo(p);
						}
						var imgWidth=slides.width();
						/* Create image */
						$(document.createElement("img"))
								.attr("src",item.Path)
								.attr("alt",item.AlternateText===null?"":item.AlternateText)
								.attr("class",item.CssClass===null?"":item.CssClass)
								.attr("height",imgHeight)
								.attr("width",imgWidth)
								.addClass("has-paging")
								.prependTo(p);
						return p;
					}
					for(i=startSlide+1;i<=data.length;i++) {
						imgArray.push(createImageObject(data[i-1],i));
					}
					for(k=1;k<startSlide;k++) {
						imgArray.push(createImageObject(data[k-1],k));
					}
					slides.prepend(imgArray.pop());
					slides.append(imgArray.shift());

					function onBefore(curr,next,opts,fwd) {
						/* on the first pass, addSlide is undefined (plugin hasn't yet created the fn yet) */
						if(!opts.addSlide) {
							return;
						}
						currentImage.text(getImageIndexFromElmId($(next).attr("id")));
						var currentPage=parseInt(currentImage.text(),10),
								prevPage=paging.find(".previous-page"),
								nextPage=paging.find(".next-page"),
								nextSlide;
						prevPage.attr("href",urlHandler.replaceOrAddQueryKeyAndValue(prevPage.attr("href"),"pagenumber"+number,
								currentPage==1?data.length:currentPage-1));
						nextPage.attr("href",urlHandler.replaceOrAddQueryKeyAndValue(nextPage.attr("href"),"pagenumber"+number,
								currentPage==data.length?1:currentPage+1));

						/* have we added all our slides? */
						if(opts.slideCount==data.length) {
							return;
						}
						/* shift or pop from our slide array  */
						nextSlide=fwd?imgArray.shift():imgArray.pop();
						/* add our next slide */
						opts.addSlide(nextSlide,fwd===false);
					}
					function onAfter(curr,next,opts,fwd) {
						var currentIndex = next.id.split('_')[2];
						$(".currentPage").html(currentIndex);
					}
					slides.cycle({
						continuous: 1,
						startingSlide: 1,  // start on the slide that was in the markup 
						timeout: 0,
						speed: speed,
						fastOnEvent : 300,
						prev: slideSelector+" .previous-page",
						next: slideSelector+" .next-page",
						before: onBefore,
						after: onAfter
					});
					if($(".slide").hasClass('paused')){
						slides.cycle('pause');
					}
				});
			} else {
				img=slides.find("p img");
				con.addClass("slide-done");
				if(jQuery.isFunction(callBack)) {
					callBack.call();
				}
			}
		});
	}
	return this;
};