/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="swfobject-vsdoc.js" />

var position = 1;
var windowWidth = $(window).width();
var widthDiff = Math.floor((2000 - windowWidth) / 2);
var scrollingEnabled = true;

var slideshowStart = 0;

$(document).ready(function () {

		
		/*url = url.substring(url.indexOf("#"), url.length);
		var query = GetDeeplinkValues(url);
*/
		//console.log(splitted_url);

    HandleResize();

    // Startpage has special slideshow with fading
    $(".startpage-fader").cycle({ fx: 'fade', speed: "6000", timeout: "8000" });

    // Depricated?
    $(".slide-element").eq(0).children(".forgrunn").fadeIn(2000)

    // Animate Arrow under hotels
    $('.hotels-arrow .arrow').pulse({
        marginTop: [0, -5]
    }, {
        times: 10,
        duration: 500, // duration of EACH individual animation
        easing: 'easeInOutSine', // easing function for each individual animation
        complete: function () {

        }
    });

    // Hotel icon list. Click on item will trigger slideanimation
    $(".hotel-icon a").click(function (e) {
        AnimateSlide($(this));
    });

    //$(".large-hotel-icon a img").hoverIntent(function () {
    $(".large-hotel-icon a img").hover(function () {	
        //$(this).stop().animate({ opacity: 1 }, 10);
        $(this).stop().css("opacity", "1");
    },
    function () {
        //$(this).stop().animate({ opacity: 0.4 }, 20);
        $(this).stop().css("opacity", "0.4");
    });

	$(".hotels li.close").click(function(){
		 HideHotels();
	});


    // Show hotels when hovering
    $(".hotels-header, ul.hotels, .hotels-wrapper").hoverIntent(function () {

        // Show hotels only if not in process of animating or moving between hotels
        if (!$(".hotels-wrapper-inner").is(":animated") && scrollingEnabled) {
            ShowHotels();
        }
    },
    function () {
        //if (!$(".hotels-wrapper-inner").is(":animated") && scrollingEnabled) {
        //    HideHotels();
        //}
    }
    );
    
    $(".hotels-wrapper").hoverIntent(function () {
    	var url = document.location.href.replace("http://", "");
		splitted_url=url.split("/");
		if(splitted_url[1]==null || splitted_url[1]=="" || splitted_url[1]=="default.aspx"){
			
        // Show hotels only if not in process of animating or moving between hotels
			if (!$(".hotels-wrapper-inner").is(":animated") && scrollingEnabled) {
				ShowHotels();
			}
        }
    },
    function () {
        //if (!$(".hotels-wrapper-inner").is(":animated") && scrollingEnabled) {
        //    HideHotels();
        //}
    }
    );
    
    
    

    // Init things
    InfoReady();
    MenuReady();
    ProductSheetReady();


});

function ShowHotels() {
    $(".hotels-wrapper-inner").stop().animate({ paddingTop: "0px" }, 400, "easeInOutCubic", function(){
		$(".hotels li.close").show();	
	});
}
function HideHotels() {
    $(".hotels-wrapper-inner").stop().animate({ paddingTop: "158px" }, 400, "easeInOutCubic", function(){
		$(".hotels li.close").hide();
	});
}


function AnimateSlide($clickedElement) {
    $(".hotels-arrow").load("/HideArrow.aspx");
    $('.hotels-arrow').hide();

    // Close product sheet and hide hotels while scrolling
    CloseProductSheet();
    HideHotels();

    // Slide down menu-title
    $(".menu-top-title").animate({ top: '-18px' }, 1000, 'easeInOutCubic');

    // Slide up menu container
    $(".menu").animate({ marginTop: '35px' }, 1000, 'easeInOutCubic');

    var $clickedHotel = $clickedElement.parent().parent();

    var menuID = $clickedHotel.attr("id");

    
    

   
    if ($clickedHotel.attr("position") >= currentSlide && scrollingEnabled) {

        scrollingEnabled = false;
        // Get background and foreground of next slide-element and add them
        var nextBackgroundImage = $clickedHotel.attr("background-image");
        var nextForegroundImage = $clickedHotel.attr("foreground-image");

        // Get template slide-element
        var container = $("#slidebox-template").children().first().clone();
        container.appendTo("#slider");
        var addedElement = $("#slider .template").first();
        var currentElement = $("#slider .active").first();
        addedElement.removeClass("template");
        addedElement.addClass("active");
        addedElement.addClass("slide-element");

        // Set background image based on clicked element
        addedElement.css("background-image", "url(" + nextBackgroundImage + ")");

        // Add foreground image based on clicked element
        addedElement.children(".forgrunn").first().css("background-image", "url(" + nextForegroundImage + ")");
        addedElement.children(".forgrunn").first().animate({ backgroundPosition: '0px 0px' }, 4500, 'easeInOutCubic')
        currentElement.children(".forgrunn").first().animate({ backgroundPosition: '-1000px 0px' }, 4500, 'easeInOutCubic')
        currentElement.removeClass("active");

        currentSlide = $clickedHotel.attr("position");
        var target = $(".slide-element").eq(1);
        $('#start-frame').stop().scrollTo(target, 4500,
                {
                    easing: 'easeInOutCubic',
                    offset: widthDiff,
                    onAfter: function () {
                        LoadInfoAndMenu();
                        setTimeout('cleanUpScrolling()', 100);


                    }
                }
            );

    }
    if ($clickedHotel.attr("position") < currentSlide && scrollingEnabled) {

        scrollingEnabled = false;
        // Get background and foreground of next slide-element and add them
        var nextBackgroundImage = $clickedHotel.attr("background-image");
        var nextForegroundImage = $clickedHotel.attr("foreground-image");

        // Get template slide-element
        var container = $("#slidebox-template").children().first().clone();
        container.prependTo("#slider");

        var addedElement = $("#slider .template").first();
        var currentElement = $("#slider .active").first();
        addedElement.addClass("slide-element");

        // now the position is wroong, so quickly scroll to element number 2 (the one we are viewing before animation)
        var target = $(".slide-element").eq(1);

        $('#start-frame').stop().scrollTo(target, 0, { offset: widthDiff });



        addedElement.removeClass("template");
        addedElement.addClass("active");

        // Set background image based on clicked element
        addedElement.css("background-image", "url(" + nextBackgroundImage + ")");

        // Add foreground image based on clicked element
        addedElement.children(".forgrunn").first().css("background-image", "url(" + nextForegroundImage + ")");
        addedElement.children(".forgrunn").first().css({ backgroundPosition: '-4000px 0px' });
        addedElement.children(".forgrunn").first().animate({ backgroundPosition: '0px 0px' }, 4500, 'easeInOutCubic')
        currentElement.children(".forgrunn").first().animate({ backgroundPosition: '1000px 0px' }, 4500, 'easeInOutCubic')
        currentElement.removeClass("active");


        currentSlide = $clickedHotel.attr("position");
        target = $(".slide-element").eq(0);
        //alert(target.attr("style"));
        $('#start-frame').stop().scrollTo(target, 4500,
                {
                    easing: 'easeInOutCubic',
                    offset: widthDiff,
                    onAfter: function () {
                        LoadInfoAndMenu();


                        setTimeout('cleanUpScrolling()', 100);


                    }
                }
            );
    }
        }

        function ToggleHotelIcons() {
            var currentPadding = parseInt($(".hotels-wrapper-inner").css("padding-top"));

            if (currentPadding > 0) {
                $(".hotels-wrapper-inner").animate({ paddingTop: "0px" }, 500, "easeInOutCubic");
            }
            else {
                $(".hotels-wrapper-inner").animate({ paddingTop: "156px" }, 500, "easeInOutCubic");
            }
        }

function LoadInfoAndMenu() {

    
    var url = document.location.href.replace("http://", "");
    url = url.substring(url.indexOf("#"), url.length);
    var query = GetDeeplinkValues(url);

    var bgimage = "/images/bgmaps/" + query[0] + ".jpg";
    $("#frame").css("background-image", "url(" + bgimage + ")");

    // Slide up menu container
    $(".menu").animate({ marginTop: '85px' }, 200, 'easeInOutCubic', function () {
        $(".info-wrapper").load("/document_root.aspx?menu=" + query[1] + "&random=" + Math.random(), function () { InfoReady(); });
        $(".menu-wrapper").load("/menu_top.aspx?menu=" + query[0] + "&random=" + Math.random(), function () { MenuReady() });
    });



 
    
}

function GetDeeplinkValues(deeplinkUrl)
{
    var url = deeplinkUrl.replace("http://", "");
    url = url.substring(url.indexOf("#") + 1, url.length);
    var query = url.split('/');
    query[0] = query[0].replace("root:", "");
    query[1] = query[1].replace("menu:", "");
    query[2] = query[2].replace("id:", "");
    return query;
   
}

function InfoReady() {
    $("a[rel='info-slideshow']").colorbox({ transition: "fade", opacity:0.6 });
   
    $(".show-slideshow").click(function () {
        $("a[rel='info-slideshow']").first().click();
    });

    $(".show-video a").colorbox({ iframe: true, innerWidth: 800, innerHeight: 600 });

    $(".show-map-box").each(function () {
        $(this).attr("href", $(this).attr("data-deeplink"));
    });

    // Load map document with ajax
    $(".show-map-box").click(function (e) {

        var query = GetDeeplinkValues($(this).attr("href"));

        loadUrl = "document.aspx?menu=" + query[1] + "&random=" + Math.random();
        $(".product-sheet-wrapper").show();
        $(".product-sheet-inner").load(loadUrl, function () {
            $(".product-sheet-wrapper").animate({ marginTop: -330 }, 750, 'easeInOutCubic');
            $(".info-wrapper").hide();
            ProductSheetReady();
        });

    });

    // Refresh product sheet title to corresponding hotel
    if($(".info-title").text() != ''){
        $(".hotel-title").text($(".info-title").text());
    }

    // Pulsating map indicator
    PulseArea();
   
  

}
// pulsating map indicator
function PulseArea() {
    $('.area-pulse').stop();
    $('.area-pulse').css({ width: 38, height: 38, top: 48, left: 85, opacity: 1 });
    $('.area-pulse').animate({ width: 76, height: 77, top: 29, left: 67, opacity: 0 }, 1000, null, function () {  setTimeout("PulseArea()", 400); });
   
}

function MenuReady() {

    // Replace all links with deeplinked versions
    // Exclude those with foce reload class. These have a response.redirect serverside so ajax will not work
    $(".menu a:not(.force-reload, .home-button)").each(function () {
        $(this).attr("href", $(this).attr("data-deeplink"));
    });
    $(".menu a:not(.force-reload, .home-button)").click(function (e) {

        var query = GetDeeplinkValues($(this).attr("href"));

        loadUrl = "document.aspx?menu=" + query[1] + "&random=" + Math.random();
        $(".info-wrapper").hide();
        $(".product-sheet-wrapper").show();
        $(".product-sheet-wrapper").animate({ marginTop: -330 }, 2000, 'easeInOutCubic');
        $(".product-sheet-inner").load(loadUrl, function () {
           
           
            ProductSheetReady();
        });

    });

    // Slide up menu-title
   
        $(".menu-top-title:not(.menu-top-title-start)").animate({ top: '-66px' }, 400, 'easeInOutCubic');
    

    //$(".home-button").click(function (e) {
    //    AnimateSlide($(this));
    //});
}

function ProductSheetReady() {

    HideHotels();

    $(".doc-left .colorbox-content-gallery").colorbox({ transition: "fade", opacity: 0.6, scalePhotos: true, maxHeight: "75%" });
    
    $(".product-sheet-slideshow").cycle({ fx: 'scrollHorz', startingSlide: slideshowStart });
    $(".product-sheet-slideshow").cycle('pause');
    $(".slideshow-left").click(function () {
        $(".product-sheet-slideshow").cycle('resume');
        $(".product-sheet-slideshow").cycle('prev');
        $(".product-sheet-slideshow").cycle('pause');
    });
    $(".slideshow-right").click(function () {
        $(".product-sheet-slideshow").cycle('resume');
        $(".product-sheet-slideshow").cycle('next');
        $(".product-sheet-slideshow").cycle('pause');
    });

    // Replace all submenu-links with deeplinked versions
    // Exclude area document. this has it's own logic
    $(".product-sheet-menu-item a:not(.force-reload)").each(function () {
            $(this).attr("href", $(this).attr("data-deeplink"));
    });

    $(".product-sheet-menu-item a:not(.force-reload)").click(function (e) {

        var query = GetDeeplinkValues($(this).attr("href"));

        loadUrl = "document.aspx?menu=" + query[1] + "&random=" + Math.random();
        $(".product-sheet-wrapper").show();
        $(".product-sheet-inner").load(loadUrl, function () {
            ProductSheetReady();
        });

    });

    // Bind event to product sheet close-button
    $(".product-sheet-close").click(function () {
        CloseProductSheet();

    });


   


    // Replace content with clicked list item content
    $(".doclist-item a:not(.image-scroll-item)").click(function (e) {
        e.preventDefault();
        
        $(".doclist-first").html($(this).parent().find(".doclist-hidden").html());
    });

    // Apply serialscroll to doclist-items
    $('.doclist-items').serialScroll({
        items: 'li',
        prev: '.doclist-slider-prev',
        next: '.doclist-slider-next',
        offset: 0, //when scrolling to photo, stop 230 before reaching it (from the left)
        start: 0, //as we are centering it, start at the 2nd
        duration: 1200,
        force: true,
        stop: false,
        lock: true,
        exclude: 2,
        cycle: false, //don't pull back once you reach the end
        easing: 'easeOutQuart', //use this easing equation for a funny effect
        jump: false //click on the images to scroll to them
    });


    // Back to activities link
    $(".back-to-menu a").click(function (e) {
        var query = GetDeeplinkValues($(this).attr("href"));

        loadUrl = "document.aspx?menu=" + query[1] + "&random=" + Math.random();
        $(".product-sheet-inner").load(loadUrl, function () {
            ProductSheetReady();
        });
    });

    $("a.gallery-medium").colorbox({ transition: "fade", opacity: 0.6, scalePhotos: true, maxHeight: "75%" });

    $(".gallery-items").quickPager();


    $(".product-sheet-area-a").click(function () {
        if (!$(this).parent().hasClass("product-sheet-menu-item-active")) {
            $(".doc-left .product-sheet-slideshow-wrapper").parent().toggle();
            $(".doc-left iframe").parent().toggle();
            $(".doclist-all").toggle();
            $(".doclist-header").toggle();



            // Slideshow on image-area
            $(".product-sheet-slideshow").cycle({ fx: 'scrollHorz' });
            $(".product-sheet-slideshow").cycle('pause');


            $(this).parent().parent().children().removeClass("product-sheet-menu-item-active");
            $(this).parent().addClass("product-sheet-menu-item-active");
        }
    });


    // When clicked scroller item in Area description
    $(".image-scroll-item").click(function () {
        var imagemenu = $(this).attr("data-imagemenu");
        slideshowStart = $(this).attr("data-clickposition") - 1;
        $(".product-sheet-inner").load("document.aspx?menu=" + imagemenu, function () {
            ProductSheetReady();

        });

        //        // Hide thumbnails in bottom
        //        $(".doclist-all").hide();
        //        $(".doclist-header").hide();

        //        // Destroy slideshow
        //        $('.product-sheet-slideshow').cycle('destroy');
        //        // Fjern alle aktiv-klasser
        //        $(".product-sheet-area-a").parent().removeClass("product-sheet-menu-item-active");
        //        // Legg på aktiv på Bilder
        //        $(".show-gallery").parent().addClass("product-sheet-menu-item-active");
        //        
        //        // Legg til elementet man klikket på som første item
        //        var imageurl = $(this).find("img").attr("src");
        //        var description = $(this).find("span").last().text();

        //        var clickedElement = '<div class="slideshow-element">';
        //        clickedElement += '<img width="573" height="430" alt="" src="' + imageurl + '">';
        //        clickedElement += '<div class="slideshow-description">' + description + '</div>';
        //        clickedElement += '</div>';

        //        $(".product-sheet-slideshow").html("");

        //        $(".product-sheet-slideshow").prepend(clickedElement);
        //        // Legg på alle andre items
        //        $(".doclist-slider .image-scroll-item").each(function () {
        //            var imageurl2 = $(this).find("img").attr("src");
        //            var description2 = $(this).find("span").last().text();
        //            if (imageurl != imageurl2) {
        //                var clickedElement = '<div class="slideshow-element">';
        //                clickedElement += '<img width="573" height="430" alt="" src="' + imageurl2 + '">';
        //                clickedElement += '<div class="slideshow-description">' + description2 + '</div>';
        //                clickedElement += '</div>';

        //                $(".product-sheet-slideshow").append(clickedElement);
        //            }
        //        });
        //        // Vis innhold med slideshow
        //        $(".doc-left .product-sheet-slideshow-wrapper").parent().show();
        //        $(".doc-left iframe").parent().hide();
        //        // Bind slideshow på nytt
        //        $(".product-sheet-slideshow").cycle({ fx: 'scrollHorz' });
        //        $(".product-sheet-slideshow").cycle('pause');

    });


    // Newsletter signup
    $("#signupForm").submit(function (e) {
        e.preventDefault();
        var emailaddress = $(this).find(".newsletter-signup-input").val();
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailaddress) == false) {
            alert('Ugyldig epostadresse');
            return false;
        }
        else {

            $("#signupForm").hide();
            $.post("/signup.aspx",
   				{ CMD: "SIGNUP", email: emailaddress },
   					function (data) {
   					    $(".newsletter-signup-message").html(data);
   					    $(".newsletter-signup-message").show();

   					}
				 );
        }

    });

    $(".newsletter-signup-input").focus(function () {
        $(this).val("");
    });
    $(".newsletter-signup-button").click(function (e) {
        e.preventDefault();
        $("#signupForm").submit();


    });

    // Bind sharing
    $(".share-facebook").click(function (e) {
        var shareLink = baseurl + $(this).attr("data-sharelink");
        document.location = "http://www.facebook.com/sharer.php?u=" + shareLink;
        e.stopPropagation();
        return false;
    });
    $(".share-twitter").click(function (e) {
        var shareLink = baseurl + $(this).attr("data-sharelink");
        document.location = "http://twitter.com/share?url=" + shareLink;
        e.stopPropagation();
        return false;
    });

    $(".share-blogger").click(function (e) {
        var shareLink = baseurl + $(this).attr("data-sharelink");
        var title = $(this).attr("data-title");
        document.location = "http://www.blogger.com/blog_this.pyra?t=&u=" + shareLink + "&n=Classic Norway - " + title;
        e.stopPropagation();
        return false;
    });

   

 

    // Huskeliste hovereffekt

    $(".huskeliste-add img").hover(function () {
            $(this).attr("src", "images/huskelistetag_hover.png");
        }
        ,
        function () {
            $(this).attr("src", "images/huskelistetag.png");
        }
     );

     // Huskeliste legg til

        $(".huskeliste-add").click(function () {

            var docID = $(this).attr("data-docID");
            var menuID = $(this).attr("data-menuID");
            var name = $(this).attr("data-name");

            var postData = "CMD=ADD&MENU_ID=" + menuID + "&name=" + name;
            if (docID != '') { postData += "&DOC_ID=" + docID; }

            // ajax call to add.
            $.ajax({
                type: "POST",
                url: '/h_memo_post.aspx',
                data: postData,
                success: function (data) {
                    updateHuskeliste(data)
                }
            });
        });

        $(".huskeliste-delete").click(function () {
            $.ajax({
                type: "POST",
                url: '/h_memo_post.aspx',
                data: "CMD=EMPTY",
                success: function (data) {
                    updateHuskeliste(data)
                }
            });
        });


        // Classic norway events click
        $(".events-link").click(function (e) {
            
            $(".product-sheet-inner").load("document.aspx?menu=133", function () {
                ProductSheetReady();
            });
        });

        
       


        // Reset slideshow start parameter when done
        slideshowStart = 0;


    }

function CloseProductSheet() {
    $(".product-sheet-inner").html("");
    $(".product-sheet-wrapper").animate({ marginTop: 1200 }, 750, 'easeInOutCubic', function () {
        $(".product-sheet-wrapper").hide();
        $(".info-wrapper").show();
    });
}



function updateHuskeliste(data) {
    $(".huskelistebox").load("h_memo.aspx?random=" + Math.random(), function () {

        $(".huskeliste-delete").click(function () {
            $.ajax({
                type: "POST",
                url: '/h_memo_post.aspx',
                data: "CMD=EMPTY",
                success: function (data) {
                    updateHuskeliste(data)
                }
            });
        });

    });
    
}

$(window).resize(function () {
    HandleResize();

});

function cleanUpScrolling() {
    var width = $(window).width();
    widthDiff = Math.floor((2000 - width) / 2);
    
    $(".slide-element:not(.active)").eq(0).remove();
    var target = $(".active").first();
    $('#start-frame').scrollTo(target, 0, { offset: widthDiff });
    $(".hotels").fadeIn(300);

   

    scrollingEnabled = true;
}

function HandleResize() {
    var width = $(window).width();
    widthDiff = Math.floor((2000 - width) / 2);
    //$(".slide-element").width(width);
    $("#start-frame").width(width);
    var target = $("#slider .active").first();
    $('#start-frame').stop().scrollTo(target, 0, { easing: 'easeInOutCubic', offset:widthDiff });
    
  

}




// disable selecting
// $.disableSelection(selector)
jQuery.fn.extend({
	disableSelection: function() {
		this.each(function() {
			this.onselectstart = function() { return false; };
			this.unselectable = "on";
			jQuery(this).css('-moz-user-select', 'none');
		});
	}
});

// check if page has visible scrollbar
// $.hasScrollbar()
jQuery.fn.hasScrollbar = function() {
	var scrollHeight = this.get(0).scrollHeight;

	//safari's scrollHeight includes padding
	if ($.browser.safari)
		scrollHeight -= parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom'));

	if (this.height() < scrollHeight)
		return true;
	else
		return false;
}

// get width of scrollbar (varies between browsers)
function scrollbarWidth() {
	var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
	// Append our div, do our calculation and then remove it 
	$('body').append(div);
	var w1 = $('div', div).innerWidth();
	div.css('overflow-y', 'scroll');
	var w2 = $('div', div).innerWidth();
	$(div).remove();
	return (w1 - w2);
}
