﻿/* global jQuery, $ */

// INIT SITE *************************************************
function baseInit() {
    //check if on homepage
    if (!($("body").hasClass("subpage"))) {
        // remove all scrollbars
        $("html").css({ "overflow": "hidden" });
        //load page in lightbox
        if (location.href.split("/#/")[1]) {
            var currenturl = location.href.split("/#/")[1];
            window.nonAnimOverlay("blogoverlay", currenturl, 1);
            window.prettyTitles(currenturl);
        }
    } else {
        //relocate to homepage
        location.href = "/#/" + location.href.split("/")[1];
    }

    // implement center for large screens
    if ($.browser.version != 6) {
        if ($(window).height() > 700) { $("body").addClass("largescreen"); }
        $(window).resize(function() {
            if ($(window).height() > 700) { $("body").addClass("largescreen"); }
            else { $("body").removeClass("largescreen"); }
        });
    }
    //position the dragging handles
    var buttonSpacing = 790; // 1 button every 790px
    var numberOfDragbuttons = ($(".content").width() / buttonSpacing);
    var delta = $(".content").width() / numberOfDragbuttons;
    var i;
    for (i = 0; i <= numberOfDragbuttons; i++) {
        $(".content").append("<a class=\"dragbutton\" id=\"button" + i + "\"></a>");
        $("#button" + i).css({ "left": (i * delta - ($("#button" + i).width() / 2)) });
    }

    // guess...
    $("body").addClass("hasjs");
    //position left and right buttons
    $("#wrap").append("<a href=\"#\" class=\"clickleft click\"></a><a href=\"#\" class=\"clickright click\"></a>");
    //offset site to the left
    $(".content").css("left", -(delta) * 0.85);

}
function ieInit() {
    // if ie, move blog
    if (jQuery.browser.msie) {
        $(".blog").css({ "left": "-200px" });
        $(".person a").css({ "right": "370px" });
        $(".portfolio h2").css({ "marginLeft": "12px" });
        $("#wrap").css({ "backgroundPosition": -($(window).width() / 6) + " 1px" });
    }
}
function ie6Init() {
    // if ie6, add pngfix.
    if (jQuery.browser.version == 6 && jQuery.browser.msie) {
        $(".person div, .speach, .dragbutton").ifixpng();
    }
}
// PEOPLE SWITCHER HTML UPDATER *************************************************
function peopleswitcherUpdater() {
    //add person stuff to switcher :)
    var authorname = $("#authorname").text().replace(/ /g, "&nbsp;"); // replace space with nbsp
    var authorfunc = $("#authorfunc").text().replace(/ /g, "&nbsp;");
    var authorfirstname = $("#authorfirstname").text().toLowerCase();
    window.removePng();
    $(".person a strong").html(authorname);
    $(".person a b").html(authorfunc);
    $(".person div").removeAttr("class").addClass(authorfirstname);
    $(".content").removeAttr("class").addClass("content").addClass(authorfirstname + "background");
    $("#photoauthor p").css({ "display": "none" });
    var photolink = "#photo" + authorfirstname;
    $(photolink).css({ "display": "block" });
    window.ie6Init();
    window.startOverlayButton();
}
function peopleswitcher() {
    $(".person a").click(function() {//the people switcher					
        page = "http://www.headline-interactive/Blog/homeblog/?authorid=" + $("#newauthorid").text();
        
        $("#homeblog").load(page, function() {
            
            window.peopleswitcherUpdater();
            window.startAllFunctions();
        });
        $(this).blur();
    });
}
// DRAGGABLE SITE FUNCTIONS *************************************************
function pageDragFunction() {
    // drag function
    
    $(".content").draggable({
        axis: 'x',
        stop: function dragCheck() {//check if the content borders stay within the screen									
            var offset = $(this).offset();
            if (offset.left > 0) { $(".content").animate({ left: "0px" }, 800, "easeOutBack"); }
            if (-offset.left > ($(".content").width() - $(window).width())) { $(".content").animate({ left: -($(".content").width() - $(window).width()) }, 800, "easeOutBack"); }
        }
    }).mousedown(function() {
        $(this).css({ "cursor": "url(\"/resources/images/closedhand.cur\"), -moz-grabbing" });
    }).mouseup(function() {
        $(this).css({ "cursor": "url(\"/resources/images/openhand.cur\"), -moz-grab" });
    });

    //scroll 1 screenwidth or to the border.
    $(".clickleft").click(function() {
    pageTracker._trackEvent('clickleft', 'clickleft', "/");
        var offset = $(".content").offset();
        if (-offset.left <= ($(window).width() / 2)) { $(".content").animate({ left: "0px" }, 800, "easeOutBack"); }
        if (-offset.left > ($(window).width() / 2) && -offset.left < $(".content").width()) { $(".content").animate({ left: offset.left + ($(window).width() / 2) }, 800, "easeOutBack"); }
        $(this).blur();

    });
    $(".clickright").click(function() {

    pageTracker._trackEvent('clickright', 'clickright', "/");
        var offset = $(".content").offset();
        if (-offset.left >= ($(".content").width() - (1.5 * $(window).width()))) { $(".content").animate({ left: -($(".content").width() - $(window).width()) }, 800, "easeOutBack"); }
        else { $(".content").animate({ left: offset.left - ($(window).width() / 2) }, 800, "easeOutBack"); }
        $(this).blur();
    });
    $(".leftscroll").click(function() {
        itemgo = $(this).attr("href");
        itemoffset = $(itemgo).offset().left;
        contentoffset = $(".content").offset().left;
        scrolltooffset = contentoffset - itemoffset + 40;
        if (scrolltooffset < -($(".content").width() - $(window).width())) {
            $(".content").animate({ left: -$(".content").width() + $(window).width() }, 800, "easeOutBack");
        } else {
            $(".content").animate({ left: scrolltooffset }, 800, "easeOutBack");
        }
        return false;
    });
}
// LIGHTBOX BEHAVIOUR ****************************************
function startOverlayButton() {
    //unbind everthing first :)
    $("a.startoverlay")
		.unbind("click")
		.click(function() {//initiates the lightbox overlay and sends the correct attributes
		    if ($(this).attr("href").split("www.")[0] == "http://") {
		        $(this).attr({ "href": $(this).attr("href").split(".nl")[1] });
		    } else if ($(this).attr("href").split("/")[0] == "#") {
		        $(this).attr({ "href": $(this).attr("href").split("#")[1] });
		    }
		    window.addOverlay($(this).attr("rel"), $(this).attr("href"));
		    window.prettyTitles($(this).attr("href"));
		    newhref = "#" + $(this).attr("href");
		    $(this).attr({ "href": newhref });
		});
    return false;
}
function startNonAnimOverlay() {
    $("a.startnonanimoverlay, .tags a, .navigation a").click(function() {
        if ($(this).attr("href").split("nieuwesite")[0] == "http://") {
            $(this).attr({ "href": $(this).attr("href").split(".nl")[1] });
        } else if ($(this).attr("href").split("/")[0] == "#") {
            $(this).attr({ "href": $(this).attr("href").split("#")[1] });
        }
        window.nonAnimOverlay($(this).attr("rel"), $(this).attr("href"));
        window.prettyTitles($(this).attr("href"));
        newhref = "#" + $(this).attr("href");
        $(this).attr({ "href": newhref });
    });
}
function startOpenPopup() {
    $("a.openpopup").click(function() {
    
        window.openPopup($(this).attr("href"), $(this).attr("title"), $(this).offset().top, $(this).attr("rel"));
        return false;
    });
}
function removeOverlayButton() {//remove textoverlay and overlay
    $("a.removeoverlay").click(function() {
        $(".overlay").remove();
        $(".textoverlay").remove();
        $(".popupoverlay").remove();
        document.title = "Miss Ashley Originals Inc.";
        $(this).attr({ "href": "#" });
    });
}
function slideUp() {//the textoverlay slideup animation
    topPos = ($.browser.msie && $.browser.version == 6) ? "30px" : "15%";
    $(".textoverlay").css({ "opacity": "1" }).animate({ "top": topPos }, 2000, "easeOutBack");
}
function addOverlay(classname, page) {//add an overlay and load in the page and add cruft
    pageTracker._trackEvent('addOverlay', 'addOverlay', page);
    $("html").css({ "overflow-y": "scroll" });
    $("#wrap").after("<div class=\"overlay\"></div>");

    $(".overlay").after("<div id=\"textoverlay\" class=\"textoverlay " + classname + "\"></div>");
    $(".textoverlay").css({ "top": $(window).height() }).load(page + " #main", function() {
        
        $(".overlay").animate({ "opacity": "0.8" }, 200, "linear", function() {
            setTimeout(function() { window.slideUp(); }, 1000);
        });
        $(".textoverlay").prepend("<p class=\"close\"><a href=\"/#\" class=\"removeoverlay\" title=\"Sluiten\">Sluiten</a>");

        if (classname == "portfoliooverlay") {
            window.addPortfolioOverlay();
        }

        // functions for inside the lightbox overlays
        window.startAllFunctions();
    });
}
function nonAnimOverlay(classname, page, startpage) {
    if (startpage) {
        $("html").css({ "overflow-y": "scroll" });
        $("#wrap").after("<div class=\"overlay\"></div>");

        $(".overlay").after("<div id=\"textoverlay\" class=\"textoverlay " + classname + "\"></div>").css({ "opacity": "0.5" });
        topPos = ($.browser.msie && $.browser.version == 6) ? "30px" : "15%";
        $(".textoverlay").css({ "top": topPos, "opacity": "1" });
    }

    $(".textoverlay").load(page + " #main", function() {
        
        $(".textoverlay").prepend("<p class=\"close\"><a href=\"/#\" class=\"removeoverlay\" title=\"Sluiten\">Sluiten</a>");
        if (classname == "portfoliooverlay") {
            window.addPortfolioOverlay();
        }
        window.startAllFunctions();
    });
}

function addPortfolioOverlay() {//parse menu, load contents, append.
    var menu = [];
    var links = [];
    var inserthtml = "";
    //$(".close").remove();
    if (jQuery.browser.msie) {
        $(".portfoliomenu").css({ "position": "absolute" });
        if (jQuery.browser.version == 7) {
            $(".portfoliomenu").css({ "top": "113px" });
        }
    }
    $(".portfoliomenu ul li a").each(function() {
        href = (jQuery.browser.msie) ? $(this).attr("href").split("/")[1] : $(this).attr("href");
        niceHref = href.replace(/\//g, "-");
        menu.push(niceHref);
        links.push(href);
        $(this).attr({ "href": "#" + niceHref });
    }).click(function() { return location.href.split("/")[1]; });

    for (var i = 0; i < menu.length; i++) {
        inserthtml += "<div class=\"subrowpages\" id=\"" + menu[i] + "\"></div>";
    }
    
    $(".portfoliocontent").html(inserthtml);
    $(".restofportfolio").css({ "paddingTop": $(".portfoliocontent").height() + 390 });

    for (var j = 0; j < menu.length; j++) {
        $("#" + menu[j]).load(links[j] + "index.html .portfoliocontent", function() {
            pageTracker._trackPageview(links[j]);
            $(".subrowpages").each(function() {
                $(this).prepend("<p class=\"close\"><a href=\"#\" class=\"removeoverlay\" title=\"Sluiten\">Sluiten</a>");
                window.startAllFunctions();
                window.ie7scroller();
            });
        });
    }
}
// OTHER FUNCTIONS ****************************************
function peoplePopups() {
    $(".popup").hover(
		function() { $(this).children("span").css({ "display": "block" }).animate({ "opacity": "1" }, 400, "swing"); },
		function() {
		    $(this).children("span").css({ "display": "none", "opacity": "0" });
		});
}
function rssPopups() {
    $(".rss").hover(
		function() { $(this).children("span").css({ "display": "block" }).animate({ "opacity": "1" }, 400, "swing"); },
		function() {
		    $(this).children("span").css({ "display": "none", "opacity": "0" });
		});
}


function routePlanner() {
    $(".routeheader button").click(function() {
        city = $("#vertrekpunt").val();
        window.open("http://maps.google/maps?f=d&hl=nl&geocode=&saddr=" + city + "&daddr=Headline+Interactive&sll=52.469397,5.509644&sspn=2.352512,5.141602&ie=UTF8&z=12");
        return false;
    });
}
function ie7scroller() {
    if ($.browser.msie && $.browser.version == 7) {
    }
}
function openPopup(image, text, offsettop, titletext) { //opens an image in a large popup :)
    $(".popupoverlay").remove();
    $("html").css({ "overflow-y": "scroll" });
    $("#wrap").after("<div class=\"overlay\"></div>");

    $(".this").after("<div id=\"textoverlay\" class=\"textoverlay\"></div>");
    $(".textoverlay").after('<div class="popupoverlay"><h4>' + titletext + '</h4><p>' + titletext + '</p><img class="popupoverlayimage" src="' + image + '" alt="" /></div>');
    $(".overlay").css({ "z-index": "82" });
    $("html").css({ "overflow": "hidden" });
    $(".popupoverlay")
		.prepend("<p class=\"close\"><a href=\"/#\" class=\"removeoverlay\" title=\"Sluiten\">Sluiten</a>")
		.draggable()
		.mousedown(function() { $(this).css({ "cursor": "url(\"/resources/images/closedhand.cur\"), -moz-grabbing" }); })
		.mouseup(function() { $(this).css({ "cursor": "url(\"/resources/images/openhand.cur\"), -moz-grab" }); })
		.css({ "top": offsettop - 150 });

    $(".popupoverlayimage").load(function() {
        imagewidth = $(".popupoverlayimage").width();
        $(".popupoverlay").css({ "width": imagewidth, "margin-left": -(imagewidth / 2) });
        $(".popupoverlay img").css({ "display": "visible" });
    });

    $(".popupoverlay .close").click(function() {
        $(this).parent().remove();
        $(".overlay").remove();
        return false;
    });
}
function prettyTitles(currenturl) {
    newtitle = currenturl.replace(/-/g, " "); // replace - with space
    newtitle = newtitle.replace(/\/$/, ""); //remove first and last /
    newtitle = newtitle.replace(/\//g, " - "); // replace / with -
    newtitle = newtitle.replace(/.html/, ""); // remove .html
    document.title = newtitle + " | Headline Interactive";
}
function removePng() {
    if (jQuery.browser.version == 6 && jQuery.browser.msie) {
        $(".person div, .speach").removeAttr("style");
    }
}

function startFancyBox() {
    $("a.fancy").fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'showCloseButton': true
    });
}

function startAllFunctions() {
    window.removeOverlayButton();
  
    window.startNonAnimOverlay();
    //window.startOpenPopup();
    window.startFancyBox();
    $.localScroll();
}
// INIT JQUERY ****************************************
$(document).ready(function() {

    window.baseInit();
    window.ieInit();
    window.ie6Init();
    window.pageDragFunction();
    window.peopleswitcher();
    window.peopleswitcherUpdater();
    window.startAllFunctions();
    window.startOverlayButton();
    
});
