﻿/// <reference path="jquery-1.3.1-vsdoc.js" />
/// <reference path="jquery-1.3.1.js" />
/// <reference path="json2.js" />

var AppCoreSrv = "http://www.ezface.com/Services/AppCoreSrv/AppCoreWebSrv.svc";
var UserSrv = "http://www.ezface.com/Services/UserSrv/UserWebSrv.svc";
var lastCalledFunction = undefined;
//var token = "e594fbb6-9288-4cc2-a26e-c69093dbe5ab";
//var token = "70a13b8a-d349-4e31-b567-b0f393397a93";
var attributeName = undefined;

$(document).ready(function() { initGeneral(); });

function initGeneral() {
}

function LoadContent(name) {
    attributeName = name;
    $("#MainContent", document).hide();
    ///$("#Visual", document).fadeOut("normal", null);
    $("#Visual", document).fadeTo("normal", 0.3, null);
    var ServiceUrl = AppCoreSrv + "/json/GetAttributeTree";
    var contentType = "application/json; charset=utf-8";

    var data = {
        input: {
            ApplicationID: 1,
            CountryID: 1,
            LanguageCode: 1033
        }
    };

    GetJSON(
        "POST",
        ServiceUrl,
        contentType,
        data,
        "json",
        onLoadContentSuccess,
        onLoadContentError
        );
}

function getAttributeTreeValue(data, key) {
    if (data.AttributeTrees != null)
        for (var i = 0; i < data.AttributeTrees.length; i++)
            if (data.AttributeTrees[i].Item.Attribute1 == attributeName)
                return data.AttributeTrees[i].Item;

    return undefined;
}

function onLoadContentSuccess(data) {
    if (isSecurityFailure(data.RetCode)) {
        startSession();
        lastCalledFunction = function () { LoadContent(attributeName) };
    }
    var item = getAttributeTreeValue(data);

    if (item != undefined) {
        var strTextContent = item.ValueLcs[0].Value;
        var strVisualImageUrl = item.Attribute3;
        var image = "<img src='" + "Resources/Images/" + strVisualImageUrl + "' alt='' />";

        $("#MainContent", document).html(strTextContent);
        $("#MainContent", document).fadeIn("slow", null);
        $("#Visual", document).html(image);
        ///$("#Visual", document).fadeIn("slow", null);
        $("#Visual", document).fadeTo("normal", 1, null);

        jQuery(document).trigger('VMA.onLoadContentSuccess');
    }
}

function onLoadContentError(data) {
    $(this).trigger({
        type: "VMA.OpenVMAFaceBox",
        title: "<h1>The request is not available at the moment, please try again later. </div>",
        content: ""
    });
}

function GetJSON(requestType, serviceUrl, contentType, data, dataType, onJSONSuccess, onJSONError) {
    $.ajax({
        type: requestType,
        url: serviceUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        dataType: "json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader('authorization', token);
        },
        success: function(data) {
            //alert("Success: " + data);
            onJSONSuccess(data);

        },
        error: function(data) {
            //alert("errorIN :: " + data.toString());
            onJSONError(data);
        }
    });

}

function OpenDocument(FileName) {
    var myWindow = window.open(FileName, "_blank", "width=1003,height=768,scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes");
    myWindow.moveTo(0, 0);
}

function goToAncore(ancoreIndex, resourceRequest) {
    //location.href=location.href.substring(0,location.href.indexOf("#")) + ancoreIndex;
    //alert("goToAncore");
    //if(!window.fleXenv || ! fleXenv.scrollTo(ancoreIndex,ancoreIndex)) {
    //location.href=location.href.substring(0,location.href.indexOf("#")) + "" + ancoreIndex;
    //}
    if (resourceRequest != undefined) {
        LoadVisual(resourceRequest);
    }

    if (!window.fleXenv || !fleXenv.scrollTo(ancoreIndex, ancoreIndex)) {
        location.href = location.href.substring(0, location.href.indexOf("#")) + "#" + ancoreIndex;
    }
    /* hesido: scroll to element whose fleXcroll parent does not need to be known, this is new in this beta. */
    /* I also changed the goToAnchor function to accept just the id without # for processing simplicity.*/
    /* What you see is fallback method if fleXcroll does not work. */
}

function TryVirtualMirror() {
    //Used to be Application Url
    //window.document.referrer = "web.aspx";
    window.location.href = "Application/EZfaceApplication.aspx";
}

//Calling from flashupload
function UploadPhotoNow() {
    window.location = "Login.aspx";
}

function ForceDownloadImage(ImageUrl) {
    //alert(ImageUrl);
    window.open("DownloadImage.aspx?ImageUrl=" + ImageUrl, "_blank", "width=10,height=10,scrollbars=yes,resizable,status=yes,toolbar=yes,menubar=yes,location=yes");
}

function openLightBox(selector) {
    //alert("openLightBox");
    ///$("#"+selector).selector('#imgLoader').width(700);
    //$('#LightBox').append('<div id="EZLoader"><img id="imgLoader" src="Resources/Images/EZLoader.gif" alt="" /></div>');
    ///$('#EZLoader').stop().animate({ opacity: 0.1 });
    //alert($("#" + selector).find('#LightBox').width());
    //alert($("#" + selector).find('#LightBox').height());

    $("#" + selector).find('#LightBox').append('<div id="EZLoader"><img id="imgLoader" src="Resources/Images/EZLoader.gif" alt="" /></div>');
    $("#" + selector).find('#LightBox').find('#EZLoader').stop().animate({ width: $("#" + selector).width(), height: $("#" + selector).height(), opacity: 0.5 });
}

function closeLightBox() {
    $('#EZLoader').remove();
}

/////////////////////////////////////////////////////
function LoadVisual(name) {
    attributeName = name;
    $("#Visual", document).fadeOut("normal", null);
    var ServiceUrl = AppCoreSrv + "/json/GetAttributeTree";
    var contentType = "application/json; charset=utf-8";

    var data = {
        input: {
            ApplicationID: 1,
            CountryID: 1,
            LanguageCode: 1033
        }
    };

    GetJSON(
        "POST",
        ServiceUrl,
        contentType,
        data,
        "json",
        onLoadVisualSuccess,
        onLoadVisualError
        );
}

function onLoadVisualSuccess(data) {
    if (isSecurityFailure(data.RetCode)) {
        startSession();
        lastCalledFunction = function () { LoadVisual(attributeName) };
    }
    var item = getAttributeTreeValue(data);

    if (item != undefined) {
        var strVisualImageUrl = item.Attribute3;
        var image = "<img src='" + "Resources/Images/" + strVisualImageUrl + "' alt='' />";
        $("#Visual", document).html(image);
        $("#Visual", document).fadeIn("slow", null);
    }
}

function onLoadVisualError(data) {
    $(this).trigger({
        type: "VMA.OpenVMAFaceBox",
        title: "<h1>The request is not available at the moment, please try again later. </div>",
        content: ""
    });
}

function startSession() {
    var contentType = "application/json; charset=utf-8";
    var ServiceUrl = UserSrv + "/json/StartSession";
        var data = {
            input: {
                Session: {
                    ApplicationID: 9,
                    IPAddress: clientIPAddress
                }
            }
        };

        ///WSManager.postJSON(url, data, onComplete, onError, metadata);

        GetJSON(
        "POST",
        ServiceUrl,
        contentType,
        data,
        "json",
        function (data) {
            token = data.Token,
            updateToken(),
            lastCalledFunction(attributeName)
        },
        onStartSessionError
        );
    }

    function onStartSessionError() {
    }

function isSecurityFailure(retCode) {
    if (retCode == -6 || retCode == -7 || retCode == -5 || retCode == -4)
        return true;
    else
        return false;
}

function updateToken() {
    var ServiceUrl = "XMLHttpRequest.aspx?action=UpdateToken&Token=" + token;
    $.ajax({
        url: ServiceUrl
    });
}
