﻿var BaseSiteUrl;

var DefaultAnimationDuration = 400;
var AnimationDirections = {
    Left: { Value: 0, Name: "Left" },
    Right: { Value: 1, Name: "Right" }
};

var WindowHeight = $.browser.viewHeight;
var WindowWidth = $.browser.viewWidth;
var HeaderHeight = $("#header").height();
var FooterHeigth = $("#footer").height();

var iScrollCapable = $.browser.mobile && $.browser.touch;
var iScrollEnabled = false;
var myScroller;

if (iScrollCapable) {

    document.addEventListener('DOMContentLoaded', loaded, false);

    
    function loaded() {
        myScroller = new iScroll('wrapper', { bounceLock: true });
        iScrollEnabled = true;
    }

    document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    document.addEventListener('DOMContentLoaded', loaded, false);

    
}

function Initialise(baseSiteUrl, specificAppInitialisationFunction, specificAppInitialisationFunctionParams) {

    BaseSiteUrl = baseSiteUrl;
    
    MoveAuxFrameLeft();

    specificAppInitialisationFunction(specificAppInitialisationFunctionParams);
    
    $("#pageMask").width(WindowWidth);
}

function MoveAuxFrameLeft() {
    var auxWrapper = $("#auxWrapper");
    auxWrapper.css("left", "-" + $("#wrapper").width().toString() + "px");
    SetLoader($("#auxWrapper .PageContent"));
}

function MoveAuxFrameRight() {
    var auxWrapper = $("#auxWrapper");
    auxWrapper.css("left", $("#wrapper").width().toString() + "px");
    SetLoader($("#auxWrapper .PageContent"));
}

function SetLoader(containerElement) {
    containerElement.html("<div id='Loader'>Loading Content</div>");
}

function DestroyScroller() {
    if (iScrollEnabled) {
        myScroller.destroy();
        myScroller = null;    
    }else {
        $('#wrapper').css('overflow', 'hidden');
    }
    
}

function SwapCurrentWrapper(newAuxElem) {
    newAuxElem.attr('id', 'tempAuxWrapper');
    $("#auxWrapper").attr('id', 'wrapper');
    $("#tempAuxWrapper").attr('id', 'auxWrapper');
    $("#auxWrapper .PageContent").empty();
}

function AnimatePage(contentControlPath, getParamsFunction, animationDirection, animationDuration, successCallBackFunction) {
    $(".ShareFrame").fadeOut(0);
    $("li.Share").removeClass("Current").unbind('click');

    DestroyScroller();
    var horizontalMove = "";
    switch (animationDirection) {
        case AnimationDirections.Right:
            MoveAuxFrameLeft();
            break;
        case AnimationDirections.Left:
            MoveAuxFrameRight();
            horizontalMove = "-";
            break;
    }

    horizontalMove = horizontalMove + $(this).width().toString() + "px";

    $("#wrapper").animate({ left: horizontalMove, useTranslate3d: true }, animationDuration, function () { });
    $("#auxWrapper").animate({ left: '0px', useTranslate3d: true }, animationDuration, function () {
        AnimatedPageRenderAjaxContent(contentControlPath, getParamsFunction, successCallBackFunction);
    });

}

function RenderAjaxContent(contentControlPath, getParamsFunction, successCallBackFunction) {

    UserControlView.RenderWithParams
    (
		contentControlPath,
		JSON.stringify(getParamsFunction()),
		function (result) {

		    var cleaned = $("<div />").html(result);

		    PopulatePage(ParseResult(cleaned), false);

		    if (successCallBackFunction != null)
		        successCallBackFunction();

		    if (iScrollEnabled)
		        setTimeout(function () { myScroller.refresh(); }, 0);
		}
	);

}

function AnimatedPageRenderAjaxContent(contentControlPath, getParamsFunction, successCallBackFunction) {

    UserControlView.RenderWithParams
    (
		contentControlPath,
		JSON.stringify(getParamsFunction()),
		function (result) {

		    var cleaned = $("<div />").html(result);
		    PopulatePage(ParseResult(cleaned), true);
		    SwapCurrentWrapper($("#wrapper"));

		    if (successCallBackFunction != null)
		        successCallBackFunction();
		    
		    if (iScrollEnabled) {
		        myScroller = new iScroll('wrapper', { bounceLock: true });
		    } else {
		        $('#wrapper').css('overflow', 'auto');
		    }
		}
	);
}

function ParseResult($html) {
    var data = { MainNavigation: "", PageContent: "", ControlPanel: "" };

    data.MainNavigation = $html.find("#MainNavigationPlaceHolderContent").html();
    data.PageContent = $html.find("#PagePlaceHolderContent").html();
    data.ControlPanel = $html.find("#ControlPanelPlaceHolderContent").html(); 

    return data;
}

function PopulatePage(pageParts, animated) {
    InsertMainNavigation(pageParts.MainNavigation);
    InsertPageContent(pageParts.PageContent, animated);
    InsertPageControlPanel(pageParts.ControlPanel);
}

function InsertMainNavigation(html) {
    $("#MainNavigationPlaceHolder").html(html);  
}

function InsertPageContent(html, animated) {
    if(animated)
        $("#auxWrapper .PageContent").html(html);
    else
        $("#wrapper .PageContent").html(html);
}

function InsertPageControlPanel(html) {
    $("#ControlPanelPlaceHolder").html(html);
}

function InitialiseControlPanel(shareLink) {
    $(".ShareFrame").fadeOut(0);
    var elemControlPanel = $("ul.ControlPanel");

    SelectControlPanelButton(elemControlPanel.find("li#" + $(".ControlPanelGroup > .Current").attr("id") + "Button a"));

    elemControlPanel.find("li").not(".Share").children("a").click(function () {
        SelectControlPanelButton($(this));
        return false;
    });

    if (shareLink == "") {
        elemControlPanel.find("li.Share").css("display", "none");
    } else {

        elemControlPanel.find("li.Last").removeClass("Last");

        elemControlPanel.find("li.Share").addClass("Last").css("display", "inline-block").toggle(
            function () {
                $(this).addClass("Current");
                $(".ShareFrame").fadeIn();
            },
            function () {
                $(this).removeClass("Current");
                $(".ShareFrame").fadeOut();
            }
        );

        SetShareButtons(shareLink);
    }

    elemControlPanel.css("left", (WindowWidth / 2) - (elemControlPanel.width() / 2) + "px");

}

function SelectControlPanelButton(elemControlButton) {

    var controlPanel = elemControlButton.parent().parent();
    controlPanel.children("li").not(".Share").removeClass("Current");
    elemControlButton.parent().addClass("Current");

    var controlPanelGroup = $(".ControlPanelGroup");
    controlPanelGroup.find(".ControlPanelGroupPage").removeClass("Current");
    var currentGroupPage = controlPanelGroup.children("#" + elemControlButton.attr("href"));
    currentGroupPage.addClass("Current");

    //controlPanelGroup.height($("#PropertyTitle").height() + currentGroupPage.height() + 20);

    if (iScrollEnabled) {
        setTimeout(function () { myScroller.refresh(); }, 0);
    }

}

function SetShareButtons(shareLink) {

    $(".ShareFrame").empty();

    var html = "<span id='ShareFacebook'></span><br /><span id='ShareTwitter'></span><br /><span id='ShareEmail'></span>";
    $(".ShareFrame").html(html);

    stWidget.addEntry({
        "service": "facebook",
        "element": document.getElementById('ShareFacebook'),
        "url": BaseSiteUrl + shareLink,
        "title": "Colliers International New Zealand Commercial Property Consultants",
        "type": "vcount",
        "text": "",
        "image": BaseSiteUrl + "PublicSite/Mobile/Skin/Images/Colliers-International.jpg",
        "summary": "Click the link to view property listing"
    });

    stWidget.addEntry({
        "service": "twitter",
        "element": document.getElementById('ShareTwitter'),
        "url": BaseSiteUrl + shareLink,
        "title": "Colliers International New Zealand Commercial Property Consultants",
        "type": "vcount",
        "text": "",
        "image": BaseSiteUrl + "PublicSite/Mobile/Skin/Images/Colliers-International.jpg",
        "summary": "Click the link to view property listing"
    });

    stWidget.addEntry({
        "service": "email",
        "element": document.getElementById('ShareEmail'),
        "url": BaseSiteUrl + shareLink,
        "title": "Colliers International New Zealand Commercial Property Consultants",
        "type": "vcount",
        "text": "Email",
        "image": BaseSiteUrl + "PublicSite/Mobile/Skin/Images/Colliers-International.jpg",
        "summary": "Click the link to view property listing"
    });
}

function EnableHomeLink(contentControlPath, getParamsFunction, successCallBackFunction, animate ) {
    $("#HomeButton").click(function () {
    
        if (!(animate == true)) {
            RenderAjaxContent(
                contentControlPath,
                getParamsFunction,
                successCallBackFunction
            );
        } else {
            AnimatePage(
                contentControlPath,
                getParamsFunction,
                AnimationDirections.Right,
                DefaultAnimationDuration,
                successCallBackFunction
            );
        }
        return false;
    });
}

function SerializeArray(dataItems, customNameAttribute) {
    
    var o = {};
    var a = dataItems;
    $.each(a, function () {
        var itemNameAttrValue = $("[name='" + this.name + "']").attr(customNameAttribute);
        if (o[itemNameAttrValue] !== undefined) {
            if (!o[itemNameAttrValue].push) {
                o[itemNameAttrValue] = [o[this.name]];
            }
            o[itemNameAttrValue].push(this.value || '');
        }
        else {
            o[itemNameAttrValue] = this.value || '';
        }
    });  return o;
}

function AddDataPairToSerializedArray(dataItems, key, value) {
    dataItems[key] = value;
}

function CosmosWriteFlash() {}



