
/* Fix for Chrome and ASP.NET Ajax */
//Sys.Browser.WebKit = {};

//if (navigator.userAgent.indexOf('WebKit/') > -1) {
//    Sys.Browser.agent = Sys.Browser.WebKit;
//    Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
//    Sys.Browser.name = 'WebKit';
//}

/* jScale Image Scaler v1.01
* Last updated: Aug 6th, 2009: Fixed bug when "ls (largest side)" option is used
* Author: JavaScript Kit at http://www.javascriptkit.com/
* Visit http://www.javascriptkit.com/script/script2/jScale/ for full source code
*/
if (typeof jQuery != 'undefined') {


    jQuery.jScale = {
        getnewSize: function (side, nvalue) {
            var otherside = (side == "w") ? "h" : "w"
            if (typeof nvalue == "undefined" || nvalue == null) //if this side has no explicit size set, scale it
                var newSize = this.ndimensions[otherside] * this.odimensions[side] / this.odimensions[otherside]
            else
                var newSize = (/%/.test(nvalue)) ? parseInt(nvalue) / 100 * this.odimensions[side] : parseInt(nvalue)
            this.ndimensions[side] = Math.round(newSize)
        },
        getnewDimensions: function ($, imgref, setting, callback) {
            //create temporary floating image to get original image's true dimensions (in case width/height attr set)
            var $tempimg = $('<img src="' + imgref.src + '" style="position:absolute; top:0; left:0; visibility:hidden" />').prependTo('body')
            this.odimensions = { w: $tempimg.width(), h: $tempimg.height()} //get image dimensions
            var sortbysize = (this.odimensions.w > this.odimensions.h) ? ["w", "h"] : ["h", "w"] //array to determine [largerside, shorterside]
            this.ndimensions = {}
            if (typeof setting.ls != "undefined") { //if setting.ls defined
                setting[sortbysize[0]] = setting.ls //set the correct side to the longest side's value setting
                setting[sortbysize[1]] = null
            }
            var sortbyavail = (setting.w) ? ["w", "h"] : (setting.h) ? ["h", "w"] : [] //check which side to work on based on availibility (which property is set by user)
            if (sortbyavail.length > 0) {
                this.getnewSize(sortbyavail[0], setting[sortbyavail[0]]) //work on side with property that's defined for sure first
                this.getnewSize(sortbyavail[1], setting[sortbyavail[1]]) //work on side with property that may or may not be defined last
                var callbackfunc = callback || function () { }
                if (setting.speed > 0)
                    $(imgref).animate({ width: this.ndimensions.w + 'px', height: this.ndimensions.h + 'px' }, setting.speed, callbackfunc)
                else {
                    $(imgref).css({ width: this.ndimensions.w + 'px', height: this.ndimensions.h + 'px' })
                    callbackfunc.call(imgref)
                }
            }
            $tempimg.remove()
        }
    };

    jQuery.fn.jScale = function (setting, callback) {
        return this.each(function () { //return jQuery obj
            var imgref = this
            if (typeof setting == "undefined" || imgref.tagName != "IMG")
                return true //skip to next matched element
            if (imgref.complete) { //account for IE not firing image.onload
                jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
            }
            else {
                $(this).bind('load', function () {
                    jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
                })
            }
        })
    };
}

function validateLogin() {
    for (i = 0; i < loginElements.length; i++) {

        var value = document.getElementById(loginElements[i]).value;
        if (value == null || value == "") {
            document.getElementById(validationLabels[i]).style.display = "inline";
            document.getElementById(loginElements[i]).focus();
            return false;
        } else {
            document.getElementById(validationLabels[i]).style.display = "none";
        }
    }

    return true;
}

function validateAddPhone() {
    for (i = 0; i < addPhoneElements.length; i++) {

        // only check the ass device page
        if (document.getElementById(addPhoneElements[i]) == null) { return true };

        var value = document.getElementById(addPhoneElements[i]).value;
        if (value == null || value == "") {
            document.getElementById(addPhoneValidationLabels[i]).style.display = "inline";
            document.getElementById(addPhoneElements[i]).focus();
            return false;
        } else {
            document.getElementById(addPhoneValidationLabels[i]).style.display = "none";
        }
    }
    return true;
}

function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}

function DeviceStatusCheck() {
    if (typeof (PageMethods) != "undefined") {
        var DeviceStatusCheckMethod = eval('PageMethods.' + deviceStatusCheckMethod);

        if (DeviceStatusCheckMethod != null && registeredDevices != "") {
            DeviceStatusCheckMethod(registeredDevices, OnDeviceStatusCheckComplete, OnDeviceStatusCheckTimeout, OnDeviceStatusCheckError);
        }
        else {
            //No Action
        }
    }
}


function OnDeviceStatusCheckComplete(result) {
    if ((result != null) && (result != deviceStatus)) {
        location.reload(true);
    }

    if (result == null) {
        alert('Redirect!');
    }

    window.setTimeout('DeviceStatusCheck()', 20000);
}
function OnDeviceStatusCheckTimeout() {
    //alert('TODO:  Add timeout logic');
}
function OnDeviceStatusCheckError() {
    //alert('TODO:  Add error logic');
}

/********* TinyMCE init for editing ***************/
var tinymcearr;

function initPageHtmlEditor() {
    tinymcearr = $('.htmlEditor').rte({
        css: ['/secure/resources/style.aspx?type=default', '/secure/resources/style.aspx?type=domain'],
        controls_rte: rte_toolbar2,
        controls_html: html_toolbar
    });
}

function initContentHtmlEditor() {
    tinymcearr = $('.htmlEditor').rte({
        css: ['/secure/resources/style.aspx?type=default', '/secure/resources/style.aspx?type=domain'],
        controls_rte: rte_toolbar3,
        controls_html: html_toolbar
    });
}

function CopyFirstContentToDest(destDomId) {
    $(destDomId).text(tinymcearr[0].get_content());
}
function CopyFirstContentToDestAttr(destDomId, attr) {
    $(destDomId).attr(attr, (tinymcearr[0].get_content()));
}


////////////////////////////////////////
/// Deployment Queue                  //
////////////////////////////////////////

function DeploymentWait(show) {
    if (show == true) {
        $get('deploymentqueuewait').style.display = "block";
        $('.boxproduct a').css('display', 'none');
        $('.boxproduct')
                .fadeTo('fast', 0.5)
                .css('cursor', 'wait');
    }
    else {
        $get('deploymentqueuewait').style.display = "none";
        $('.boxproduct a').css('display', 'block');
        $('.boxproduct')
                .fadeTo('fast', 1)
                .css('cursor', 'default');
    }
}

function CloseDeployment(deploymentId, deviceId) {
    DeploymentWait(true);
    revival.selfservice.secure.webservices.deploymentqueue.CloseDeployment(deploymentId, deviceId, OnCompleteShowQueue, DepQueueError, DepQueueTimeOut);
}

function RestartDeployment(deploymentId, deviceId) {
    DeploymentWait(true);
    revival.selfservice.secure.webservices.deploymentqueue.RestartDeployment(deploymentId, deviceId, OnCompleteShowQueue, DepQueueError, DepQueueTimeOut);
}

function AddDeploymentToQueue(deploymentId, deviceId) {
    DeploymentWait(true);
    revival.selfservice.secure.webservices.deploymentqueue.AddDeployment(deploymentId, deviceId, OnCompleteShowQueue, DepQueueError, DepQueueTimeOut);
}

function OnCompleteShowQueue(result) {
    DeploymentWait(false);
    $get('deploymentQueueContent').innerHTML = result;
}

function DepQueueError() {
    DeploymentWait(false);
    window.clearTimeout(deploymentTimer);
}

function DepQueueTimeOut() {
    DeploymentWait(false);
    window.clearTimeout(deploymentTimer);
}
function UpdateDeploymentQueue() {
    revival.selfservice.secure.webservices.deploymentqueue.Update(OnUpdateDeploymentComplete, DepQueueError, DepQueueTimeOut);
}

function OnUpdateDeploymentComplete(result) {
    $get('deploymentQueueContent').innerHTML = result;
    deploymentTimer = window.setTimeout(UpdateDeploymentQueue, 20000);
}
var deploymentTimer;


////////////////////////////////////////////
/// Device-registration clear phonenumber //
////////////////////////////////////////////
function PhonenumberClearWait(show) {
    if (show == true) {
        $('.modalpopupbox .introduction span').css('display', 'none');
        $('.modalpopupbox .nav').css('display', 'none');
        $('#modalpopupboxloading').css('display', 'block');
    }
    else {
        $('.modalpopupbox .introduction span').css('display', 'block');
        $('.modalpopupbox .nav').css('display', 'block');
        $('#modalpopupboxloading').css('display', 'none');
    }
    return;
}

function ClearPhonenumberOnDevice(deviceId) {
    // Show Loading and hide buttons
    PhonenumberClearWait(true);
    revival.selfservice.secure.webservices.device.ClearPhonenumber(deviceId, OnSuccessClearPhonenumber, ClearPhonenumberError, ClearPhonenumberError);
}

function OnSuccessClearPhonenumber(result) {
    //PhonenumberClearWait(false);
    // Hide box / Cancel
    //$('.modalpopupbox #cancelButton').click();
    // Continue with Registration

    if (result == false) {
        ClearPhonenumberError();
    } else {
        $('#ctl00_mainContent_btnNext').click(); // Register
    }
    return;
}

function ClearPhonenumberError() {
    // Show error
    PhonenumberClearWait(false);
    $('.modalpopupbox .introduction span').text('<%= GetString("portalnewdevicewizardclearnumbererror") %>');
    $('.modalpopupbox #ctl00_confirmButton').css('display', 'none');

}



function RemoveExternalProductFromBasket(source, id) { revival.selfservice.extensions.webservices.basket.RemoveExternalProduct(source, id, OnCompleteShowBasket, OnError, OnTimeOut); }
function RemoveDomainProductFromBasket(source, id) { revival.selfservice.extensions.webservices.basket.RemoveDomainProduct(source, id, OnCompleteShowBasket, OnError, OnTimeOut); }
function RemoveFormProductFromBasket(source, id) { revival.selfservice.extensions.webservices.basket.RemoveFormProduct(source, id, OnCompleteShowBasket, OnError, OnTimeOut); }

function GetExternalProductAccessories(externalProductId) { revival.selfservice.extensions.webservices.externalproducts.GetExternalProductAccessories(externalProductId, OnCompleteExternalProductAccessories, OnError, OnTimeOut); }

function GetConfirmationUser(username) { revival.selfservice.extensions.webservices.basket.GetUser(username, "confirmationbasketuser.xsl", OnCompleteConfirmationUser, OnError, OnTimeOut); }

function OnTimeOut(arg) {
    alert('<%= GetString("portalgenericoperationtimeout") %>');
}

function OnError(arg) {
    //DEBUG: var obj= eval(arg); var str = '<%= GetString("portalgenericoperationerror") %>\n'; for (prop in obj) { str += prop + ': ' + obj[prop] + '\n'; }

    alert('<%= GetString("portalgenericoperationerror") %>');
}

function OnCompleteShowBasket(result) {
    $get('basketcontents').innerHTML = result;

    if (result == "") {
        $get('confirmBasketButtonTrigger').style.display = "none";
        $get('emptymessage').style.display = "inline";
        $get('basketcontents').style.display = "none";
    }
    else {
        $get('confirmBasketButtonTrigger').style.display = "block";
        $get('emptymessage').style.display = "none";
        $get('basketcontents').style.display = "block";
    }


}

function OnCompleteConfirmationBasket(result) {
    $get('basketcontentsmessage').innerHTML = result;
}

function onOrderForOthersSearch() {
    GetConfirmationUser($get("personalinfousernameinput").value);
    $get("personalinfousernameinputvalue").value = $get("personalinfousernameinput").value;
    $get("personalinfousernameinput").value = "";
}

function OnCompleteConfirmationUser(result) {
    $get('personalinfodata').innerHTML = result;
}

var confirming = false;

function onBasketConfirmation() {
    if (confirming) {
        return false;
    }

    confirming = true;

    $get("waitWorking").style.display = "inline";

    $get("cancelBasketButton").disabled = true;
    $get("cancelBasketButton").style.display = "none";

    $get("ctl00_leftContent_leftContent_confirmBasketButton").disabled = true;

    return true;
}

function onBasketCancelConfirmation() {
    if (confirming) {
        return false;
    }

    var userNameInput = $get("personalinfousernameinput");

    if (userNameInput != null) {
        GetConfirmationUser('<%= this.CurrentUser.Name %>');

        userNameInput.value = "";
    }

    //$find('confirmBasketExBehaviour').hide();
    $get("confirmationbasket").style.display = "none";
    $get("confirmBasketNav").style.display = "none";
    $get("confirmCancelled").style.display = "block";

    return true;
}

function ShowExternalProductInfo(elementid) {
    $get('genericDialogContent').innerHTML = unescape($get(elementid).innerHTML);
    $get('genericDialogContent').style.height = "480px";
    $get('genericDialog').style.height = "500px";

    $find('genericDialogExBehaviour').show();
}

function onGenericDialogClose() {
    if (genericDialogCloseAction == "") {
        $find('genericDialogExBehaviour').hide();
        return true;
    }
    else {
        $get('genericDialogLoader').style.display = 'block';
        var url = genericDialogCloseAction;
        genericDialogCloseAction = "";
        return location.replace(url);
    }
}

function OnCompleteExternalProductAccessories(result) {
    $get('genericDialogContent').innerHTML = result;
    $get('genericDialogContent').style.height = "480px";
    $get('genericDialog').style.height = "500px";

    $find('genericDialogExBehaviour').show();
}

