if (!a10.skins) {a10.skins = {}};
a10.skins.uploadTimeout = 3 * 60 * 1000;
a10.skins.apiTimeout = 20 * 1000;
a10.skins.timeoutHandler = null;
a10.skins.tempMetaInfo = "";
a10.skins.uploading = false;
a10.skins.fromSignup = false;
a10.skins.fromSignin = false;
a10.skins.skinCheck = false;
a10.skins.currentSkinId="";
a10.skins.currentSkin=null;
function skinInfo( skinId,url,width,height,position,textcolor) {

    this.skinId = skinId;
    this.url = url;
    this.width = width;
    this.height = height;
    this.position = position;
    this.textcolor = textcolor;
}

//opera requires special handler for cross document communication
if(window.opera) {
    window.document.addEventListener("message", function(ev) {
        eval(ev.data);
    }, false);
}

a10.skins.clearTimeout = function() {
    if(a10.skins.timeoutHandler) {
        clearTimeout(a10.skins.timeoutHandler);
        a10.skins.timeoutHandler = null;
    }
}

/**
 * Callback function to handle upload API calls by updating UI with meta info generated by the newly uploaded image
 *
 * @param response server response object with image meta info
 */
a10.skins.uploadHandler = function(response) {
    a10.skins.uploading = false;

    a10.skins.clearTimeout();

    if(response.status == "success") {
        //update thumbnails
        $('skinPreview1').src = response.element.thumbnailUrl;
        $('skinPreview2').src = response.element.thumbnailUrl;
        a10.skins.tempMetaInfo = response.element;

        $('skinId').value = response.element.id;

        //update file info on the UI
        var fileSize = (response.element.filesize/1024 > 0) ? Math.round(response.element.filesize/1024) + "KB" : "1KB";
        $('skinInfoLabel').innerHTML = response.element.width + "x" + response.element.height + ", " + fileSize;
        $('skinInfoSpan').innerHTML = response.element.width + "x" + response.element.height + ", " + fileSize;
        $('skinname').value = response.element.name;

        if(response.element.uid && _skinUserId == '') {
            //new anon user created, use the ID for subsequent calls
            _skinUserId = response.element.uid;

            //update cookie with new PUID
            a10.skins.setPUID(response.element.uid);
        }

        a10.skins.uploadStep3();
    } else {
        a10.skins.uploadStep1(true);
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage("uploadErrorLabel", response.element.errMsg);
    }
}

a10.skins.setPUID = function(uid) {
    //update cookie with new PUID
    _skinUserId = "";
    var nextYr = new Date();
    nextYr.setTime(nextYr.getTime() + 31536000000);
    document.cookie = "PUID=" + uid + "; expires=" + nextYr.toGMTString() +"; path=/; domain=ask.com";
    myStuffMenu.updateStatus();
}

/**
 * Callback function to handle update meta info API calls by moving to the next step if successful, else display
 * error message from server side
 *
 * @param response server response object
 */
a10.skins.metaInfoHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        a10.skins.uploadStep4();
    } else {
        a10.skins.uploadStep3();
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage("uploadNameErrorLabel", response.element.errMsg);
    }
}

/**
 * Shows error for the specified field by changing the field border to red and adding an error icon to the label of
 * the field.
 *
 * @param fieldId html ID of field to indicate error
 */
a10.skins.showError = function(fieldId) {
    if($(fieldId).type != "checkbox") {
        $(fieldId).style.border = "solid 1px #cc0000";
    }

    var html = $(fieldId + "Label").innerHTML.toLowerCase();

    if(html.indexOf("<img") == -1) {
        //error is not displayed yet
        $(fieldId + "Label").innerHTML = '<img src="'+a10.strings.skins_errorurl+'" style="padding-right:5px;padding-left:0;margin-left:0">' + $(fieldId + "Label").innerHTML;
    }
}

/**
 * Clears error for the specified field by restoring the field border to the default color and removing the error icon
 *
 * @param fieldId html ID of field to clear error from
 */
a10.skins.clearError = function(fieldId) {
    if($(fieldId).type != "checkbox") {
        $(fieldId).style.border = "solid 1px #9699A2";
    } /*else {
        $(fieldId).style.border = "solid 1px #FFF";
    }*/

    var html = $(fieldId + "Label").innerHTML.toLowerCase();
    if(html.indexOf("<img") != -1) {
        $(fieldId + "Label").innerHTML = $(fieldId + "Label").innerHTML.substring(html.indexOf(">") + 1);
    }
}

/**
 * Sets alignment of the preview image to the specified position
 *
 * @param valign vertical alignment (center, top, or bottom)
 * @param align horizontal alignment (center, left, or right)
 * @param alignImg html IMG element that was clicked
 */
a10.skins.setAlign = function(valign, align, alignImg) {
    $("skinposition").value = valign + " " + align;
    a10.skins.drawAlign(alignImg, false, "skinposition");
}

/**
 * Sets alignment of the preview image in the edit dialog to the specified position
 *
 * @param valign vertical alignment (center, top, or bottom)
 * @param align horizontal alignment (center, left, or right)
 * @param alignImg html IMG element that was clicked
 */
a10.skins.setEditAlign = function(valign, align, alignImg) {
    $('skinEditPosition').value = valign + " " + align;
    a10.skins.drawAlign(alignImg, true, "skinEditPosition");
}

/**
 * Sets the text color for the skin in the dialog
 *
 * @param color color of the text (dark or light)
 */
a10.skins.setTextColor = function(color) {
    $('skincolor').value = color;
    a10.skins.drawTextColor(false);
}

/**
 * Sets the text color for the skin in the edit dialog
 *
 * @param color color of the text (dark or light)
 */
a10.skins.setEditTextColor = function(color) {
    $('skinEditColor').value = color;
    a10.skins.drawTextColor(true);
}

/**
 * Draws the text label to indicate what color is current selected for the text color
 */
a10.skins.drawTextColor = function(isEdit) {

    if( ( isEdit && $('editText1') != null) || ( !isEdit && $('text1') != null )){
        var color = $(!isEdit ? 'skincolor' : 'skinEditColor').value;
        if(color == 'dark') {
            $(!isEdit ? 'text1' : 'editText1').style.border = "solid 1px #ff0004";
            $(!isEdit ? 'text2' : 'editText2').style.border = "solid 1px #fff";
            $(!isEdit ? 'skinTextColorLabel' : 'skinEditTextColorLabel').innerHTML = a10.strings.skins_lighttext;
        } else {
            $(!isEdit ? 'text1' : 'editText1').style.border = "solid 1px #fff";
            $(!isEdit ? 'text2' : 'editText2').style.border = "solid 1px #ff0004";
            $(!isEdit ? 'skinTextColorLabel' : 'skinEditTextColorLabel').innerHTML = a10.strings.skins_darktext;
        }

        if(!isEdit) {
            $('skinTextSpan').innerHTML = $('skinTextColorLabel').innerHTML;
        }
     }
}

/**
 * Draws the preview on the thumbnail
 *
 * @param boundaryId html id of preview mask
 * @param position mask position
 * @param previewWidths dimension of the thumbnail and preview mask
 */
a10.skins.drawPreview = function(boundaryId, position, previewWidths) {
    var boundary = $(boundaryId);

    if(position == 'top left') {
        boundary.style.left = previewWidths[0] - previewWidths[2] + "px";
        boundary.style.top = previewWidths[1] - previewWidths[3] + "px";
    } else if(position == 'bottom left') {
        boundary.style.left = previewWidths[0] - previewWidths[2] + "px";
        boundary.style.top = "0";
    } else if(position == 'center center') {
        boundary.style.left = ((previewWidths[0] - previewWidths[2])/2) + "px";
        boundary.style.top = ((previewWidths[1] - previewWidths[3])/2) + "px";
    } else if(position == 'top center') {
        boundary.style.left = ((previewWidths[0] - previewWidths[2])/2) + "px";
        boundary.style.top = previewWidths[1] - previewWidths[3] + "px";
    } else if(position == 'bottom center') {
        boundary.style.left = ((previewWidths[0] - previewWidths[2])/2) + "px";
        boundary.style.top = "0";
    } else if(position == 'top right') {
        boundary.style.left = "0";
        boundary.style.top = previewWidths[1] - previewWidths[3] + "px";
    } else if(position == 'bottom right') {
        boundary.style.left = "0";
        boundary.style.top = "0";
    } else if(position == 'center right') {
        boundary.style.left = "0";
        boundary.style.top = ((previewWidths[1] - previewWidths[3])/2) + "px";
    } else if(position == 'center left') {
        boundary.style.left = previewWidths[0] - previewWidths[2] + "px";
        boundary.style.top = ((previewWidths[1] - previewWidths[3])/2) + "px";
    }

    boundary.style.display = '';
}

/**
 * Updates previews with the alignment selected by the user
 *
 * @param selectedAlign html DOM element that was selected by the user
 */
a10.skins.drawAlign = function(selectedAlign, isEdit, positionInputId) {
    var position = $(positionInputId).value;

    var prefix = 'align';
    if(isEdit) {
        prefix = "editAlign";
    }

    //reset selected border
    for(var i = 1; i < 10; i++) {
        $(prefix + i).style.border = "solid 1px #fff";
    }

    if(!isEdit) {
        $('skinAlignDiv').className = selectedAlign.className;

        //updated previews in steps 3 & 4
        a10.skins.drawPreview('skinBoundary', position, [200, 130, 255, 161]);
        a10.skins.drawPreview('skinBoundary2', position, [130, 85, 164, 104]);
    } else {
        a10.skins.drawPreview('skinEditBoundary', position, [200, 130, 255, 161]);
    }

    //updated selected border
    if(selectedAlign != null) {
        selectedAlign.style.border = "solid 1px #ff0004";
    }
}

/**
 * Resets the error label for fields
 */
a10.skins.resetErrorLabels = function() {
    var allErrorLabels = ['uploadErrorLabel', 'uploadUrlErrorLabel', 'uploadTermErrorLabel']
    for(var i = 0; i < allErrorLabels.length; i++) {
        $(allErrorLabels[i]).style.display = 'none';
    }
}

/**
 * Checks whether current skin matches with the user's selected skin in mystuff
 */
a10.skins.checkSelectedSkin = function() {
    if(a10.skins.isAuthenticated()) {
        a10.skins.prepRequest();
        $('skinretrieveform').submit();
    }

}

/**
 * Sets up UI to display step 1 of the upload process
 *
 * @param preserver whether to preserve value currently in the textfields
 */
a10.skins.uploadStep1 = function(preserve) {
    if(!Cookie.isEnabled()) {
        window.location = _urlPrefix + "skinscookies";
        return false;
    }

    //check selected skin vs current skin

    a10.skins.clearError('skinurl');
    a10.skins.clearError('skinfile');
    a10.skins.clearError('skinterm');

    $('skinStep2').style.display = 'none';
    $('skinStep3').style.display = 'none';
    $('skinStep4').style.display = 'none';
    $('skinStep1').style.display = '';

    a10.skins.resetErrorLabels();

    window.skinUploadDialog.title = a10.strings.skins_upload + ' <span style="color:#000;font-weight:normal">' + a10.strings.skins_step1 + '</span>';
    $('dialogTitle').innerHTML = a10.strings.skins_upload + ' <span style="color:#000;font-weight:normal">' + a10.strings.skins_step1 + '</span>';

    if(!preserve) {
        //clear old values
        $('skinurl').value = "";
        try {
            $('skinfile').value = "";
        } catch(e) {
            //ignore this error. different browser have diff behavior on this
        }
        $('skinname').value = "";
        $('skinposition').value = "center center";
        $('skincolor').value = "light";
        $('skinterm').checked = false;
    }

    a10.skins.fromSignup = false;

    //init masks if IE6
    if(a10.browser.isIE6()) {
        var pixelUrl = $('skinPreview1').src;
        var img = $('skinBoundary');
        if(img.src.indexOf('pixl.gif') == -1) {
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='" + img.src + "')";
            img.src = pixelUrl;
        }

        img = $('skinBoundary2');
        if(img.src.indexOf('pixl.gif') == -1) {
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='" + img.src + "', sizingMethod='scale')";
            img.src = pixelUrl;
        }
    }
}

/**
 * Sets up UI to display step 2 of the upload process
 */
a10.skins.uploadStep2 = function() {
    $('skinStep1').style.display = 'none';
    $('skinStep3').style.display = 'none';
    $('skinStep4').style.display = 'none';
    $('skinStep2').style.display = '';
}

/**
 * Sets up UI to display step 3 of the upload process
 */
a10.skins.uploadStep3 = function() {
    a10.skins.clearError("skinname");

    $('skinStep1').style.display = 'none';
    $('skinStep2').style.display = 'none';
    $('skinStep4').style.display = 'none';
    $('skinStep3').style.display = '';
    $('dialogTitle').innerHTML = a10.strings.skins_upload + ' <span style="color:#000;font-weight:normal">' + a10.strings.skins_step2 + '</span>';

    $('uploadNameErrorLabel').style.display = 'none';

    a10.skins.drawAlign($('align5'), false, "skinposition");
    a10.skins.drawTextColor();
    $('skinname').focus();
}

/**
 * Sets up UI to display step 3 of the upload process
 */
a10.skins.uploadStep4 = function() {
    $('skinStep1').style.display = 'none';
    $('skinStep2').style.display = 'none';
    $('skinStep3').style.display = 'none';
    $('skinStep4').style.display = '';

    a10.skins.fromSignup = false;

    if(!a10.skins.isAuthenticated()) {
        $('signinPane').style.display = '';
    } else {
        $('signinPane').style.display = 'none';
    }

    $('dialogTitle').innerHTML = a10.strings.skins_upload + ' <span style="color:#000;font-weight:normal">' + a10.strings.skins_step3 + '</span>';
    var skinName = $('skinname').value;
    $('skinTitleSpan').innerHTML = skinName.substr(0, Math.min(50, skinName.length)) + (skinName.length > 50 ? "..." : "");

    if(window._mystuffSignInCallback) {
        //unregister signin handler
        window.mystuffSignInCallback = window._mystuffSignInCallback;
    }
    $('skinUseNow').focus();
}

/**
 * Shows upload related error by setting the error message display to the specified msg and shaking the dialog.
 *
 * @param id html id of error label
 * @param msg error message to show
 */
a10.skins.showErrorMessage = function(id, msg) {
    a10.skins.shaking = true; //ensure that only one shake loop is going at any time

    var errorLabel = $(id);
    errorLabel.style.display = '';
    errorLabel.innerHTML = msg;

    a10.anim.shake('dialog', 20, 1, function () {a10.skins.shaking = false});
}

/**
 * Starts the upload process by validating user input, display error messages if any, then upload the image to the
 * server side
 *
 */
a10.skins.startUpload = function() {
    if(a10.skins.shaking) {
        return; //do nothing if dialog is still shaking
    }

    //validate entry
    var skinurl = a10.util.trim($('skinurl').value);
    if(skinurl == '' && a10.util.trim($('skinfile').value) == '') {
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage('uploadErrorLabel', a10.strings.skins_emptyselection);
        a10.skins.showError('skinfile');
        a10.skins.showError('skinurl');
        a10.skins.clearError('skinterm');
    } else if(skinurl != '' && !/^http:\/\//i.test(skinurl)) {
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage('uploadUrlErrorLabel', a10.strings.skins_urlinvalid);
        a10.skins.clearError('skinfile');
        a10.skins.showError('skinurl');
        a10.skins.clearError('skinterm');
    } else if(skinurl != '' && $('skinfile').value != '') {
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage('uploadErrorLabel', a10.strings.skins_urlfile);
        a10.skins.showError('skinfile');
        a10.skins.showError('skinurl');
        a10.skins.clearError('skinterm');
    } else if(!$('skinterm').checked) {
        a10.skins.resetErrorLabels();
        a10.skins.showErrorMessage('uploadTermErrorLabel', a10.strings.skins_tos);
        a10.skins.showError('skinterm');
        a10.skins.clearError('skinfile');
        a10.skins.clearError('skinurl');
    } else {
        a10.skins.uploadStep2();

        if(!a10.skins.isAuthenticated()) {
            $('skinuid').value = _skinUserId; // set userId
        }
        a10.skins.prepRequest();
        a10.skins.uploading = true;

        try {
            $('skinform').submit();
            var func = function() {
                a10.skins.cancelUpload();

                if(_impressionUrl) { //timeout impression
                    new Image().src = _impressionUrl + "&rnd=" + new Date().getTime();
                }

                a10.skins.uploadHandler({status : "error", element : {errMsg : a10.strings.skins_error}})
            };
            a10.skins.timeoutHandler = setTimeout(func, a10.skins.uploadTimeout);
        } catch (e) {
            //assume invalid file in IE
            a10.skins.uploadStep1(true);
            a10.skins.resetErrorLabels();
            a10.skins.showErrorMessage('uploadErrorLabel', a10.strings.skins_badfile);
            a10.skins.showError('skinfile');
            a10.skins.clearError('skinurl');
            a10.skins.clearError('skinterm');
        }
    }
    return false;

}

/**
 * Sets the skin attributes by validating user input, display error messages if any, then submitting the info to the
 * server side
 */
a10.skins.setAttrs = function() {
    if(a10.skins.shaking) {
        return false; //do nothing if dialog is still shaking
    }

    if(a10.util.trim($('skinname').value) != '') {
        a10.skins.uploadStep2();

        if(!a10.skins.isAuthenticated()) {
            $('skinuid2').value = _skinUserId; // set userId
        }
        a10.skins.prepRequest();
        a10.skins.submitWithTimeout('skinattrform', a10.skins.metaInfoHandler);
    } else {
        $('uploadNameErrorLabel').style.display = '';
        $('uploadNameErrorLabel').innerHTML = a10.strings.skins_namerequired;

        a10.skins.showError("skinname");
        a10.skins.shaking = true;
        a10.anim.shake('dialog', 20, 1, function() {a10.skins.shaking=false;});
    }
    return false;
}

a10.skins.applyCurrentSkin = function(metaInfo) {
    a10.skins.setSkinCookie(metaInfo.id, metaInfo.url, metaInfo.width, metaInfo.height, metaInfo.color, metaInfo.position);

    if($('skinCredit')) { //if on homepage
        a10.skins.applySkin(metaInfo.url, metaInfo.width, metaInfo.height, metaInfo.color, metaInfo.position, metaInfo.credit, true);
    }

    var peelMe = $('peelPromo');
    if(peelMe) {
        peelMe.style.display = 'none';
    }
}

/**
 * Saves user skin selected and updates the current skin to the skin that was just uploaded.
 */
a10.skins.saveAndUseSkin = function() {
    //cookie value validation
    var metaInfo = a10.skins.tempMetaInfo;

    a10.skins.setSkinCookie(metaInfo.id, metaInfo.url, metaInfo.width, metaInfo.height, $('skincolor').value, $('skinposition').value);

    a10.skins.prepRequest();
    $('selectedSkinId').value = metaInfo.id;

    if(!a10.skins.isAuthenticated()) {
        $('skinuid3').value = _skinUserId; // set userId
    }

    $('selectfn').value = "a10.skins.selectHandler";
    a10.skins.submitWithTimeout('skinselectform', a10.skins.selectHandler);
    a10.skins.uploadStep2();
    a10.skins.tempMetaInfo = null;
}

a10.skins.isAuthenticated = function() {
    var auid = Cookie.getCookie("AUID");
    return auid != null && auid != '';
}

a10.skins.getColors = function(textColor) {
    var linkColor, selectedColor;
    if(textColor == 'light') {
        linkColor = "#FFFFFF";
        selectedColor = "#CC0000";
    } else if(textColor == 'dark' || textColor == null || a10.util.trim(textColor) == '') { //assume empty as dark
        linkColor = "#666666";
        selectedColor = "#CC0000";
    } else{
        var colors = textColor.split(" ");
        linkColor = colors[0];
        selectedColor = colors[1];
    }
    return [linkColor, selectedColor];
}

/**
 * Sets the skins cookie with the specified values
 *
 * @param skinId id of skin
 * @param url url to skin image
 * @param width width of image in pixels
 * @param height height of image in pixels
 * @param textColor text color (dark or light)
 * @param position anchoring position of the skin
 */
a10.skins.setSkinCookie = function(skinId, url, width, height, textColor, position) {
    //link colors
    var colors = a10.skins.getColors(textColor);
    var linkColor = colors[0];
    var selectedColor = colors[1];

    var cookieValue = "id="+ skinId +"&su=" + escape(url) + "&" + "w="+width+"&h="+height+"&lc="+linkColor+"&sc="+selectedColor+"&sa=" + escape(position);

    var nextYr = new Date();
    nextYr.setTime(nextYr.getTime() + 31536000000);
    document.cookie = "sk2=" + cookieValue + "; expires=" + nextYr.toGMTString() +"; path=/; domain=ask.com";

    //setting skin back to empty, raise metro flag to 2
    if(skinId == "" && Cookie.getCookie("skm") == "1") {
        Cookie.setCookie("skm", "2", nextYr, "/", "ask.com");
    }
}

a10.skins.getCurrentSkin = function() {
    var skinCookie = Cookie.getCookie("sk2", true);
    var skin  = {};

    if(skinCookie != null && skinCookie != '') {
        var parts = skinCookie.split("&");

        for(var i = 0; i < parts.length; i++) {
            var pair = parts[i].split("=");
            skin[pair[0]] = pair[1];
        }
    }

    skin['su'] = unescape(skin['su']);
    return skin;
}

a10.skins.currentSkinHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        if(response.element.id != '') {
            var skin = a10.skins.getCurrentSkin();
            var colors = a10.skins.getColors(response.element.color);
            /*alert(skin['id'] + " " + response.element.id + ", "+ skin['sa']  + " " + response.element.position
                + ", "+  skin['lc']  + " " + colors[0]  + ", "+  skin['sc']  + " " + colors[1]);
            */if(skin['id'] == response.element.id) { /*&& skin['sa'] == response.element.position
               && skin['lc'] == colors[0] && skin['sc'] == colors[1]) {*/
                //skins matched, no action required
                return;
            }

            var peelPromo = $('peelPromo');
            peelPromo.style.display = 'none';
        }

        a10.skins.setSkinCookie(response.element.id,  response.element.url, response.element.width, response.element.height, response.element.color ? response.element.color : "", response.element.position ? response.element.position : "");
        a10.skins.applySkin(response.element.url, response.element.width, response.element.height, response.element.color ? response.element.color : "", response.element.position ? response.element.position : "", null, true);
    } else {
        var peelPromo = $('peelPromo');
        a10.skins.setSkinCookie('', '', '', '', '', '');

        var userCookie = Cookie.getCookie("user");
        
        if(!peelPromo) {
            a10.skins.applySkin('', null, null, null, null, null, true);
        }
    }
}

a10.skins.toggleDownArrows = function(show) {
    var spans = null;
    if($('oli_2col')){
        spans = $('oli_2col').getElementsByTagName("span");
    }
    else {
        spans = $('oli').getElementsByTagName("span");
    }
    for(var i = 0; i < spans.length; i++) {
        if(spans[i].className == "darrow") {
            spans[i].style.display = show ? '' : 'none';
        }
    }

    if($('mli_2col')){
        spans = $('mli_2col').getElementsByTagName("span");
    }
    else {
        if($('mli')){
            spans = $('mli').getElementsByTagName("span");
        }
    }
    for(var i = 0; i < spans.length; i++) {
        if(spans[i].className == "darrow") {
            spans[i].style.display = show ? '' : 'none';
        }
    }
}

a10.skins.updateLinkStyles = function(color) {
    var wrapper = $('wrapper');
    if(wrapper != null) {
        var colors = a10.skins.getColors(color);
        window.navColor = colors[0];
        window.navSelectedColor = colors[1];

        $('footerCopyright').style.color = navColor;
        $('footerLinks').style.color = navColor;
        $('mslabel') ? $('mslabel').style.color = navColor : null;
        if($('mli_2col')){
            $('mli_2col').style.color = navColor;
            $('oli_2col').style.color = navColor;
        }
        else{
            $('mli') ? $('mli').style.color = navColor : null;
            $('oli').style.color = navColor;
        }
        if($('eli')) {
            $('eli').style.color = navColor; //france does not have eraser link yet
        }
        $('skinCredit').style.color = navColor;

        var anchors = $('tnav').getElementsByTagName("a");
        for(var i = 0; i < anchors.length; i++) {
            if(anchors[i].className == "navSelected") {
                anchors[i].style.color = navSelectedColor;
            } else {
                anchors[i].style.color = navColor;
            }
        }

        anchors = $('footerLinks').getElementsByTagName("a");
        for(var i = 0; i < anchors.length; i++) {
            anchors[i].style.color = navColor;
        }
    }
}

a10.skins.updateSkinPosition = function(position) {
    var wrapper = $('wrapper');
    if(wrapper != null) {
        wrapper.style.backgroundRepeat = "no-repeat";
        if(position != '' && position != "undefined" && position != null) {
            wrapper.style.backgroundPosition = position;
        } else {
            wrapper.style.backgroundPosition = "bottom center";
        }
    }
}

/**
 * Applies the skin setting to the current page
 *
 *
 */
a10.skins.applySkin = function(url, width, height, color, position, credit, skipMakeHP, noDelay) {
    var wrapper = $('wrapper');
    if(wrapper != null) {

        if(url == '') {
            wrapper.style.backgroundImage = "none";
            if(document.getElementById("hotspot") !=null ){
                document.getElementById("hotspot").style.display="none";
            }
            a10.skins.toggleDownArrows(true);
            setTimeout(function() {
                if($(window.skinApplyingDialog.id).style.display != 'none') {
                    window.skinApplyingDialog.hide();
                }

                if(!skipMakeHP) {
                    a10.hp.showSkinsMakeHomepage();
                }
            }, 2000);
            a10.skins.updateSkinPosition(position);
        } else {
            var img = new Image();

            _startTime = new Date().getTime();

            var func = function() {
                a10.skins.updateSkinPosition(position);
                $("wrapper").style.backgroundImage = "url("+url+")";
                if(document.getElementById("hotspot") !=null && _locale == "us" && _shareSkinApplicable=="true" && _isEraser=="false"){
                    document.getElementById("hotspot").style.display = "block";
                    if(_shareSkinImpressionUrl && _shareSkinImpressionUrl != null && _shareSkinImpressionUrl.length > 0) { 
                        new Image().src = _shareSkinImpressionUrl + "&rnd=" + new Date().getTime();
                    }
                }
                if(credit) {
                    $('skinCredit').innerHTML = a10.strings.skins_credit + " " + credit;
                }
                else {
                    $('skinCredit').innerHTML = "" /*TRES-11243: Remove "Photo by" when the skin author is empty*/
                }

                if($(window.skinApplyingDialog.id).style.display != 'none') {
                    window.skinApplyingDialog.hide();
                }

                if(!skipMakeHP) {
                    a10.hp.showSkinsMakeHomepage();
                }
            }

            img.onload = function () {
                var now = new Date().getTime();
                var diff = now - _startTime;
                if(diff < 2000 && !noDelay) {
                    setTimeout(func, 2000-diff);
                } else {
                    func();
                }
            };
            img.src = url;
            a10.skins.toggleDownArrows(false);
            wrapper.style.minHeight = 0;
        }


        a10.skins.updateLinkStyles(color);

        if(width != null && width != '') {
            _maxHeight = height;
            wrapper.style.maxWidth = width +"px";
            wrapper.style.maxHeight = height +"px";

            if(a10.browser.isIE6()) {
                wrapper.style.setExpression("width", '(document.body.clientWidth > '+width+' ? "'+width+'px" : "auto")');
                wrapper.style.setExpression("height",  '(document.body.clientHeight > '+height+' ? "'+height+'px" : "100%")');
            }

            windowSizeChanged(); //update vertical position of entire wrapper
            a10.hp.repositionSkinDialog();
        } else {
            //remove max width/height constraint
            _maxHeight = 0;
            $("wrapper").style.top = "0";
            wrapper.style.maxWidth = 'none';
            wrapper.style.maxHeight = 'none';

            if(a10.browser.isIE6()) {
                wrapper.style.setExpression("width", '(document.body.clientWidth < 800 ? "798px" : "auto")');
                wrapper.style.setExpression("height", '(document.body.clientHeight < 600 ? "598px" : "100%")');
            }
        }

        //update edit status
        a10.skins.updateCurrentSkinStatus();

        if($('promo')) {
            $('promo').innerHTML = ""; //clearing out promo text
        }

        if($('flashPeelPromo')) {
           $('flashPeelPromo').style.display = 'none';
        }
    }


}

/**
 * Callback function to handle select skin API calls by hiding the dialog and reloading the page to the new skin
 */
a10.skins.selectHandler = function(response) {
    a10.skins.clearTimeout();

    //window.skinUploadDialog.hide();
    if(response.status == "success") {
        if(response.element.uid) {
            _skinUserId = response.element.uid;
            a10.skins.setPUID(response.element.uid);
        }
    } else {
        alert(response.element.errMsg);
    }

    if($('origin') && $('origin').value == "10579") { //do special datran logic to append guaid to refresh url
        var url = window.location.toString();
        var startIndex = url.indexOf("guaid");
        if(startIndex != -1) {
            var guaid = url.substring(startIndex + 6, url.indexOf("&", startIndex));
            _reloadUrl += "&guaid=" + guaid;
        }
    }

    if($('shareskinorigin') && $('shareskinorigin').value == "13050") {
        var url = window.location.href.toString();
        var startIndex = url.indexOf("?");
        if(startIndex != -1) {
            _reloadUrl = url + "&o=13050";
        }else{
            _reloadUrl = url + "?o=13050";
        }
    }

    if (_skinFtcPromoOrigin) {
        _reloadUrl = _reloadUrlDisableFtc;
    }

    window.location.replace(_reloadUrl + "&sknr=1");
}

/**
 * Saves newly uploaded skin. The current implementation saves the skin at step 3, so just hide the dialog
 */
a10.skins.saveSkin = function() {
    a10.skins.tempMetaInfo = null;
    window.skinUploadDialog.hide();
    if(!a10.hp) {
        a10.skins.refreshPage();
    }
}

/**
 * Handles clicks to the x button for the upload dialog. This also handles the case where the user is trying to sign
 * up for a new mystuff account during the upload process.
 */
a10.skins.closeUploadDialog = function() {
    if(a10.skins.fromSignup) {
        a10.skins.fromSignup = false;
        return true;
    }

    if(a10.skins.fromSignin) {
        //from sign in, do not delete temp skin
        a10.skins.fromSignin = false;
        return true;
    }

    a10.skins.cancelUpload();

    if(a10.skins.tempMetaInfo) {
        //call delete API with temp skin id
        a10.skins.prepRequest();
        $('deleteSkinId').value = a10.skins.tempMetaInfo.id;

        if(!a10.skins.isAuthenticated()) {
            $('skinuid4').value = _skinUserId;
        }

        $('skindeleteform').submit();
        a10.skins.tempMetaInfo = "";
    }
    return true;
}

/**
 * Cancels the upload API call by replacing the src of the hidden iframe to blank to cancel the current http request.
 */
a10.skins.cancelUpload = function() {
    if(a10.skins.uploading) {
        $('hif').src = "about:blank";
        a10.skins.uploading = false;
    }
}

/**
 * Cancels the upload dialog by canceling the upload form submission if it's still active, then deleting any
 * intermediary skin that has not be completely saved, and lastly, closing the dialog.
 *
 * @param hideDialog true to hide dialog, false otherwise
 */
a10.skins.cancelUploadDialog = function(hideDialog) {
    a10.skins.cancelUpload();

    if(a10.skins.tempMetaInfo) {
        //call delete API with temp skin id
        a10.skins.prepRequest();
        $('deleteSkinId').value = a10.skins.tempMetaInfo.id;

        if(!a10.skins.isAuthenticated()) {
            $('skinuid4').value = _skinUserId;
        }

        $('skindeleteform').submit();
        a10.skins.tempMetaInfo = "";
    }

    if(hideDialog) {
        window.skinUploadDialog.hide();
    }
    return false;
}

/**
 *  Callback function to handle delete skin API calls
 */
a10.skins.deleteHandler = function(response) {
    a10.skins.clearTimeout();

    //do nothing for now
    if(response.status == "error") {
        alert(response.element.errMsg);
    }
}

/**
 * Key down handler to help detect the enter key in textfield and submitting the form to mimic default browser
 * form submission behaviors
 *
 * @param e key event
 * @param callback function to invoke on enter key
 */
a10.skins.keyDownHandler = function(e, callback) {
    var event = window.event ? window.event : e;
    var keycode = event.keyCode;

    if (keycode == 13) {
        a10.event.cancelDefaultAction(e);
        callback();
        return false;
    }
}

a10.skins.signupStep1 = function() {
    a10.skins.fromSignup = true;
    window.skinUploadDialog.hide();

    //register signin handler
    window.mystuffSignUpCallback = function() {
        a10.skins.setPUID("");
        window.skinUploadDialog.show();
        a10.skins.uploadStep4();
        window.mystuffSignUpCallback = null;
    }

    ask.mystuff.SignUp.step1();
    ask.mystuff.SignUp.onClose = function() {
        window.skinUploadDialog.show();
        a10.skins.uploadStep4();
        ask.mystuff.SignUp.onClose = null;
    }

    window.signupDialog.show();
}

/**
 * Hides the upload dialog and opens mystuff sign in modal
 */
a10.skins.signin = function() {
    a10.skins.fromSignin = true;
    window.skinUploadDialog.hide();
    window._mystuffSignInCallback = window.mystuffSignInCallback; //backup callback handler

    //register signin handler
    window.mystuffSignInCallback = function(response) {
        if(response.status == "success") {
            if(a10.skins.tempMetaInfo && response.element.elementmap) {
                a10.skins.tempMetaInfo.url = response.element.urlmap[a10.skins.tempMetaInfo.id]; //update skin url since it has been changed
                a10.skins.tempMetaInfo.id = response.element.elementmap[a10.skins.tempMetaInfo.id]; //update skin id since it has been changed
            }

            window.skinUploadDialog.show();
            a10.skins.uploadStep4();
            a10.skins.setPUID(""); //clear cookie since account has been copied and delete

            if(response.element && response.element.selectedskin) {
                //set and apply skin
                a10.skins.applyCurrentSkin(response.element.selectedskin);
            }
        } else {
            alert(response.element.errMsg);
        }
    };
    window.signinDialog.show();
}


a10.skins.copySaveHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        a10.skins.useSkin($('skincopyid').value, _copyMetaInfo.url, _copyMetaInfo.width, _copyMetaInfo.height, $('skincopycolor').value, $('skincopyposition').value, true);
        a10.skins.applySkin(_copyMetaInfo.url, _copyMetaInfo.width, _copyMetaInfo.height, $('skincopycolor').value, $('skincopyposition').value);
    } else {
        alert(response.element.errMsg);
    }
}

a10.skins.copyUploadHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        if(response.element.uid && _skinUserId == '') {
            //new anon user created, use the ID for subsequent calls
            _skinUserId = response.element.uid;

            //update cookie with new PUID
            a10.skins.setPUID(response.element.uid);
        }

        if(!a10.skins.isAuthenticated()) {
            $('skincopyuid').value = _skinUserId;
        }

        _copyMetaInfo = response.element;

        $('skincopyid').value = response.element.id;
        a10.skins.prepRequest();
        $('skinemailsaveform').submit();
    } else {
        alert(response.element.errMsg);
    }
}


/**
 * Displays the delete skin dialog
 *
 * @param skinId id of the skin
 * @param id html id suffix of the skin
 */
a10.skins.showDeleteDialog = function(skinId, id) {
    if(!Cookie.isEnabled()) {
        window.location = _urlPrefix + "skinscookies";
        return false;
    }

    $('skinDeleteId').value = skinId;
    $('skinDeletePreview').src = $('skt_'+id).src;
    $('skinDeleteName').innerHTML = $('skn_'+id).innerHTML;
    window.skinDeleteDialog.show();
    $('deleteButton').focus();
}

/**
 * Deletes the skin referenced in the delete dialog
 */
a10.skins.deleteSkin = function() {
    if(!a10.skins.isAuthenticated()) {
        $('skinDeleteUid').value = _skinUserId;
    }
    a10.skins.prepRequest();
    a10.skins.submitWithTimeout('skindeletedialogform', a10.skins.deleteSkinHandler);

}

a10.skins.deleteSkinHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        if($('skinDeleteId').value == a10.skins.getCurrentSkin()['id']) {
            var nextYr = new Date();
            nextYr.setTime(nextYr.getTime() + 31536000000);
            document.cookie = "sk2=; expires=" + nextYr.toGMTString() +"; path=/; domain=ask.com";
        }

        window.skinDeleteDialog.hide();
        a10.skins.refreshPage();
    } else {
        alert(response.element.errMsg);
    }
}

/**
 * Displays the edit skin dialog
 *
 * @param skinId id of the skin
 * @param id html id suffix (optional, if left blank, name and thumbnail url are required)
 * @param textColor color of skin text (dark or light)
 * @param position skin background position
 * @param name name of skin (optional when id is specified)
 * @param thumnailUrl url to thumbnail (optional when id is specified)
 */
a10.skins.showEditDialog = function(skinId, id, textColor, position, name, thumbnailUrl) {
    if(!Cookie.isEnabled()) {
        window.location = _urlPrefix + "skinscookies";
        return false;
    }

     if(a10.browser.isIE6()) {
        var pixelUrl = $('skinEditPreview').src;
        var img = $('skinEditBoundary');
        if(img.src.indexOf('pixl.gif') == -1) {
            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='" + img.src + "')";
            img.src = pixelUrl;
        }
     }

    if(id != null) {
        $('skineditname').value = $('skn_'+id).innerHTML;
        $('skinEditPreview').src = $('skt_'+id).src;
    } else {
        $('skineditname').value = name;
        $('skinEditPreview').src = thumbnailUrl;
    }

    $('skinEditId').value = skinId;
    $('skinEditColor').value = textColor;

    $('editStep1').style.display = '';
    $('editStep2').style.display = 'none';
    $('saveNameErrorLabel').style.display = 'none';
    a10.skins.clearError("skineditname");

    //setup preview positioning
    if(position == '') {
        a10.skins.setEditAlign('center', 'center', $('editAlign5'));
    } else {
        var spaceIndex = position.indexOf(' ');
        var positionMap = {
            "top left" : 1,
            "top center" : 2,
            "top right" : 3,
            "center left" : 4,
            "center center" : 5,
            "center right" : 6,
            "bottom left" : 7,
            "bottom center" : 8,
            "bottom right" : 9
        }
        a10.skins.setEditAlign(position.substr(0, spaceIndex), position.substr(spaceIndex+1), $('editAlign' + positionMap[position]));
    }

    a10.skins.drawTextColor(true);

    window.skinEditDialog.show();
    $('skineditname').focus();
}

/*'${result.ID}',${resultsCounter}, '${result.imageURL}', ${result.width}, ${result.height}, '${result.linkColor}', '${result.position}'*/
a10.skins.showShareDialog = function(skinId, id,url,width,height, textColor, position, thumbnailUrl) {
    if(!Cookie.isEnabled()) {
        window.location = _urlPrefix + "skinscookies";
        return false;
    }
    a10.skins.currentSkin=new skinInfo(skinId,url, width, height,position, textColor);
    if(id != null) {
            document.getElementById("share").value = $('skt_'+id).src;
        } else {
            document.getElementById("share").value = thumbnailUrl;
    }

    window.skinshareDialog.show();
    document.getElementById("dialogContent").style.padding=0;
    return false;
}


/**
 * Saves the attributes associated the skin currently being editted
 */
a10.skins.saveAttrs = function() {
    if($('skineditname').value == '') {
        a10.skins.showErrorMessage('saveNameErrorLabel', a10.strings.skins_namerequired);
        a10.skins.showError("skineditname");
        return false;
    }

    $('editStep1').style.display = 'none';
    $('editStep2').style.display = '';
    if(!a10.skins.isAuthenticated()) {
        $('skinEditUid').value = _skinUserId;
    }

    a10.skins.prepRequest();
    a10.skins.submitWithTimeout('skineditform', a10.skins.editInfoHandler);
}

/**
 * Refreshes the skin page by adding an rnd value to the url and refreshing the page
 */
a10.skins.refreshPage = function() {
    var currentURL = window.location.toString();

    if(currentURL.indexOf("#") != -1) {
        currentURL = currentURL.substring(0, currentURL.indexOf("#"));
    }
    if(currentURL.indexOf("?") == -1) {
        window.location.replace(currentURL + "?rnd=" + new Date().getTime());
    } else {
        var index= currentURL.indexOf("rnd=");
        if(index != -1) {
            currentURL = currentURL.substring(0, index);
            window.location.replace(currentURL + "rnd=" + new Date().getTime());
        } else {
            window.location.replace(currentURL + "&rnd=" + new Date().getTime());
        }
    }
}



/**
 * Callback function to edit API calls
 */
a10.skins.editInfoHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        var currentSkin = a10.skins.getCurrentSkin();
        if(currentSkin && currentSkin['id'] == $('skinEditId').value) {
            a10.skins.setSkinCookie($('skinEditId').value, currentSkin['su'], currentSkin['w'], currentSkin['h'], $('skinEditColor').value, $('skinEditPosition').value);
        }

        window.skinEditDialog.hide();
        a10.skins.refreshPage();
    } else {
        $('editStep2').style.display = 'none';
        $('editStep1').style.display = '';
        a10.skins.showErrorMessage('saveNameErrorLabel', response.element.errMsg);
    }
}

a10.skins.closeSignIn = function() {
    if(a10.skins.fromSignup) {
        a10.skins.fromSignup = false;
        setTimeout(function() {window.skinUploadDialog.show();}, 100);
    }
    return true;
}

a10.skins.editCurrent = function() {
     if(!a10.skins.isAuthenticated()) {
        $('currentskinuid').value = _skinUserId; // set userId
    }
    a10.skins.prepRequest();
    a10.skins.submitWithTimeout('skineditcurrentform', a10.skins.editCurrentSkinHandler);

    $('editStep1').style.display = 'none';
    $('editStep2').style.display = '';
    window.skinEditDialog.show();
}

a10.skins.editCurrentSkinHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        window.skinEditDialog.hide();
        $('editStep1').style.display = '';
        $('editStep2').style.display = 'none';
        $('skinEditHandler').value = "a10.skins.editCurrentSkinCompleteHandler";

        if(response.element.id) {
            //open only if current skin is valid
            a10.skins.showEditDialog(response.element.id, null, response.element.color, response.element.position, response.element.name, response.element.thumbnailUrl);
        }

    } else {
        alert(response.element.errMsg);
        window.skinEditDialog.hide();
    }
}

a10.skins.editCurrentSkinCompleteHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        a10.skins.updateLinkStyles($('skinEditColor').value);
        a10.skins.updateSkinPosition($('skinEditPosition').value);
        var currentSkin = a10.skins.getCurrentSkin();
        a10.skins.setSkinCookie(currentSkin['id'], currentSkin['su'], currentSkin['w'], currentSkin['h'], $('skinEditColor').value, $('skinEditPosition').value);
        window.skinEditDialog.hide();
    }
}

/**
 * Empty callback function
 */
a10.skins.emptyHandler = function(response) {
    a10.skins.clearTimeout();

    if(response.status == "success") {
        if(response.element.uid) {
            _skinUserId = response.element.uid;
            a10.skins.setPUID(response.element.uid);
        }
    } else {
        alert(response.element.errMsg);
    }
}

a10.skins.updateCurrentSkinStatus = function() {
    if(!$('editLink')) {
        return;
    }

    var currentSkin = a10.skins.getCurrentSkin();
    if(currentSkin['id'] != null && currentSkin['id'].length > 31) {
        //user skins have id with lenght of 32
        $('editLink').style.display = '';
        $('skinCredit').style.display = 'none';
    } else {
        $('editLink').style.display = 'none';
        $('skinCredit').style.display = (currentSkin['id'] || Cookie.getCookie("skm") == "1") ? '' : 'none';
    }
}

a10.skins.emailSkin = function(id, url, textColor, position, htmlId) {
    var colors = a10.skins.getColors(textColor);
    var payload = "id=" + id + "&su=" + escape(url) + "&lc=" + colors[0] + "&sc=" + colors[1] + "&sa=" + escape(position) + "&sn="+escape($("skn_"+htmlId).innerHTML);
    var mailUrl = _urlPrefix + "?sknd=" + (escape(payload));
        window.location = "mailto:?body=" + escape(mailUrl);
}

/**
 * Submits a form and sets a timeout that will invoke the specified handler
 *
 * formName html id of form
 * handler reference to function
 */
a10.skins.submitWithTimeout = function(formName, handler) {
    var func = function() {
        $('hif').src = "about:blank";

        if(_impressionUrl) { //timeout impression
            new Image().src = _impressionUrl + "&rnd=" + new Date().getTime();;
        }

        handler({status : "error", element : {errMsg : a10.strings.skins_error}});
    }
    $(formName).submit();
    a10.skins.timeoutHandler = setTimeout(func, a10.skins.apiTimeout);
}

/**
 * Prepares hidden iframe request by updating domain and window name. The window name hack is required for IE, where
 * the window name sometimes mysteriously disappears, causing a new window to be opened.
 */
a10.skins.prepRequest = function() {
    if(a10.browser.isIE()) {
        window.frames["hif"].name = 'hif';
    }
    document.domain = "ask.com";
}

/**
 * Shows the upload dialog by checking whether cookie is enabled, then showing the dialog and setting up
 * the upload process. If cookie is not enabled, redirect to the no cookie page
 */
a10.skins.showUploadDialog = function() {
    if(!Cookie.isEnabled()) {
        setTimeout(function() {window.location = _urlPrefix + "skinscookies"}, 10);
        return;
    }

    a10.skins.uploadStep1();
    window.skinUploadDialog.show();
}
/**
 * applies the current skin and takes to homepage
 */
a10.skins.applySkinAndGoToHP = function() {
    if(a10.hp){
        skinshareDialog.hide();
    }else
    {
        var myskin = a10.skins.currentSkin;
        if(myskin){
             a10.skins.useSkin(myskin.skinId,myskin.url,myskin.width,myskin.height,myskin.textcolor,myskin.position,false);
            }
    }
}
/**
 * Uses the skin specified by the input, shows the applying dialog, then refreshes the page to the homepage
 *
 * @param skinId id of skin
 * @param url url to skin image
 * @param width width of image in pixels
 * @param height height of image in pixels
 * @param textColor text color (dark or light)
 * @param position anchoring position of the skin
 * @param nonRefresh whether page should be redirected to HP
 */
a10.skins.useSkin = function(skinId, url, width, height, textColor, position, nonRefresh) {
    if(!Cookie.isEnabled()) {
        //using setTimeout cuz IE6 was not updating location properly
        setTimeout(function() {window.location = _urlPrefix + "skinscookies"}, 10);
        return false;
    }

    if (skinId != "ftcSpecialThumb") {
        //kick user out of FTC promo (clear cookie)
        Cookie.deleteCookie("skftc","/","ask.com");
    }

    if(skinId == "ask999999") { //assumed ID of the default
        skinId = "";
    }

    if(skinId.indexOf("ask") > -1 && document.getElementById('cc')!=null && _hotspotURL !=null){
        if(a10.browser.isIE6()) {
            document.getElementById('cc').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+_hotspotURL+"')";
        }else{
            document.getElementById('cc').src = _hotspotURL;
        }
    }

    a10.skins.setSkinCookie(skinId, url, width, height, textColor, position);

    if(skinId.indexOf("ss30009") == 0) { //assumed to be sexy skins
        //do nothing because these do not exist in mystuff
        return;
    }

    a10.skins.prepRequest();
    $('selectedSkinId').value = skinId;

    if(nonRefresh) {
        $('selectfn').value = "a10.skins.emptyHandler";
    } else {
        $('selectfn').value = "a10.skins.selectHandler";
    }

    if(!a10.skins.isAuthenticated()) {
        $('skinuid3').value = _skinUserId; // set userId
    }

    $('skinselectform').submit();

    //window.skinApplyingDialog.show();
};

