﻿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 redirectClient(url)
{
	window.location = url;
}

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 createImageDescriptionObject(imageDescription, slideWrapperParagraph, imgHeight, imgWidth) {
                        /*Create Intro/Description wrapper*/
                        var descriptionWrapper;
                        if (imageDescription.DescriptionLink !== null && imageDescription.DescriptionLink !== "") {
                            descriptionWrapper = $(document.createElement("a"));
                            descriptionWrapper.addClass("panel-link");
                            descriptionWrapper.attr("href", imageDescription.DescriptionLink);
                        } else {
                            descriptionWrapper = $(document.createElement("span"));
                        }
                        descriptionWrapper.addClass("description-wrapper");
                        descriptionWrapper.addClass("position" + imageDescription.Position);
                        if (imageDescription.NarrowTextPanel) {
                            descriptionWrapper.addClass("narrow-text-panel");
                        }
                        if (imageDescription.Position == 2) {
                            if ($(".slide div").hasClass('large-slide')) {
                                descriptionWrapperHeightOffset = 50 / 2;
                                if (imageDescription.NarrowTextPanel) {
                                    descriptionWrapperWidthOffset = 200 / 2;
                                } else {
                                    descriptionWrapperWidthOffset = 400 / 2;
                                }
                            } else {
                                descriptionWrapperHeightOffset = 40 / 2;
                                if (imageDescription.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 (imageDescription.AlignTextRight) {
                            innerDescriptionWrapper.addClass("align-text-right");
                        }
                        innerDescriptionWrapper.prependTo(descriptionWrapper);
                        /* Create Description*/
                        var span;
                        if (imageDescription.Description !== null && imageDescription.Description !== "") {
                            /* Create span */
                            span = $(document.createElement("span")).html(imageDescription.Description);
                            span.addClass("slide-description-label");
                            span.prependTo(innerDescriptionWrapper);
                        }
                        /*Create Intro*/
                        if (imageDescription.Intro !== null && imageDescription.Intro !== "") {
                            /* Create span */
                            span = $(document.createElement("span")).html(imageDescription.Intro);
                            span.addClass("slide-intro-label");
                            span.prependTo(innerDescriptionWrapper);
                        }
                        if ((imageDescription.Description !== null && imageDescription.Description !== "") || (imageDescription.Intro !== null && imageDescription.Intro !== "")) {
                            descriptionWrapper.prependTo(slideWrapperParagraph);
                        }
                    }
                    function createImageObject(item, index) {
                        /* Create paragraph */
                        var p = $(document.createElement("p"))
								.css("opacity", "0")
								.attr("id", imagePrefix + index);
                        /*Create author wrapper*/
                        if (item.Author !== null && item.Author !== "") {
                            authorWrapper = $(document.createElement("span"));
                            authorWrapper.addClass("authorWrapper");

                            authorTitle = $(document.createElement("span"));
                            authorTitle.addClass("author-title");
                            authorTitle.html(item.AuthorTitle);
                            authorTitle.prependTo(authorWrapper);

                            author = $(document.createElement("span"));
                            author.addClass("author");
                            author.html(item.Author);
                            author.prependTo(authorWrapper);

                            authorWrapper.prependTo(p);
                            p.addClass("has-author-panel");
                        }
                        var imgHeight = slides.height();
                        var imgWidth = slides.width();
                        for (descIndex = 0; descIndex < item.SlideShowImageDescriptions.length; descIndex++) {
                            createImageDescriptionObject(item.SlideShowImageDescriptions[descIndex], p, imgHeight, imgWidth);
                        }
                        /* 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;
                        }
						//$(curr).find(".description-wrapper").fadeOut(300);
                        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) {
						//$(curr).find(".description-wrapper").fadeIn(300);
                        var currentIndex = next.id.split('_')[2];
                        $(".currentPage").html(currentIndex);
                    }
                    slides.cycle({
                        continuous: 0,
                        startingSlide: 1,  // start on the slide that was in the markup 
                        timeout: speed,
						speed: 2250,  //speed of slide transition
                        fastOnEvent: 500,
                        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;
};

$(document).ready(function() {
    $("a").click(function() {
        var _clickUrl = $(this).attr("href");

        //External link:
        if ($(this).attr("href").match("http://|https://") && !$(this).attr("href").match("sweden\.se")) {
            _gaq.push(['b._trackPageview', '/exit/' + _clickUrl]);
        }
    });
    QuickSearchEnterKeyIEFix();
});

function QuickSearchEnterKeyIEFix() {
    if ($.browser.msie && $.browser.version < 9) {
        $('.quicksearch .left input').keydown(function(event) {
            if (event.keyCode == '13') {
                event.preventDefault();
                $('.quicksearch .right input').trigger('click');
            }
        });
    }
}
