/// <reference path="~/js/libraries/jquery-1.3.2-vsdoc.js" />
var pageId = ""; /*id of page control - prefixes usercontrol controls*/
var ROOT_URL = "/";

var browserAgent = navigator.userAgent.toLowerCase();
var isMsie6 = $.browser.msie && $.browser.version.substr(0, 1) == "6";
var isMsie7 = $.browser.msie && $.browser.version.substr(0, 1) == "7";
var isIphone = browserAgent.indexOf("iphone") > -1;



function debugObject(o) {
    var s = "";
    for (i in s) {
        s += i + "=" + o[i] + ", ";
    }
    return s;
} 

function SelectUtils() {
}
SelectUtils.prototype.getSelectedItem = function(id) {
    ddl = (typeof id == "string") ? $("#" + id)[0] : id;
    return ddl.options[ddl.selectedIndex];
}
SelectUtils.prototype.getSelectedValue = function(id) {
    return this.getSelectedItem(id).value;
}
SelectUtils.prototype.setSelectedValue = function(id, value, options) {
    if (options != null) {
        if (options.stripSpaces) {
            value = value.replace(" ", "");
        }
        if (options.caseInsensitive) {
            value.toLowerCase();
        }
    }

    ddl = (typeof id == "string") ? $("#" + id)[0] : id;
    for (id = 0; id < ddl.options.length; id++) {
        var oValue = ddl.options[id].value;
        if (options != null) {
            if (options.stripSpaces) {
                oValue = oValue.replace(" ", "");
            }
            if (options.caseInsensitive) {
                oValue.toLowerCase();
            }
        }
        if (oValue == value) {
            ddl.selectedIndex = id;
            break;
        }
    }
}

function FormUtils() {
}
FormUtils.prototype.getSelectedRadio = function(name) {
    var radios = $(":radio[name=" + name + "]");
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
            return radios[i];
        }
    }
    return null;
}

FormUtils.prototype.limitCharacters = function(textarea, limit, onfailure) {
    if (textarea.value.length > limit) {
        onfailure(textarea);
    }
}



var selectUtils = new SelectUtils();

var formUtils = new FormUtils();

function findInput(id) {
    //$(:input[id*='"+id+"'])[0]
    id = id.toLowerCase();
    _elements = $(":input");
    for (i = 0; i < _elements.length; i++) {
        if (_elements[i].id == null) {
            continue;
        }
        if (_elements[i].id.toLowerCase().endsWith(id)) {
            return _elements[i];
        }
    }
    return null;
}

var page = new Object();

page._onLoad = [];
page._onPreLoad = [];
page._onReSize = [];

page.ratings = function() {
    $('tr > td > input[type=radio]', $("table.star")).rating({
        onmouseover: function(el, input) {
            $(".rating-text", input[0].parentNode.parentNode.parentNode.parentNode.parentNode).html($("label", input[0].parentNode).html());
        },
        onmouseout: function(el, input) {
            var checked = $(":checked", $("name=" + input[0].name));
            var selector = "input[name=" + input[0].name + "]";
            radios = $(selector);
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) {
                    $(".rating-text", input[0].parentNode.parentNode.parentNode.parentNode.parentNode).html($("label", radios[i].parentNode).html());
                    return;
                }
            }
            $(".rating-text", input[0].parentNode).html("");
        }
    });


    var radios = $('tr > td > input[type=radio]', $("table.star")).mouseout();
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
            $(".rating-text", radios[i].parentNode.parentNode.parentNode.parentNode.parentNode).html($("label", radios[i].parentNode).html());
        }
    }
}

page.onload = function(fn) {
    if (jQuery.inArray(fn, this._onLoad) == -1) {
        this._onLoad[this._onLoad.length] = fn;
    }
}
page.load = function() {
    for (var i = 0; i < this._onLoad.length; i++) { this._onLoad[i](); }
}

page.onpreload = function(fn) {
    if (!inArray(fn, this._onPreLoad)) {
        this._onPreLoad[this._onPreLoad.length] = fn;
    }
}
page.preload = function() {
    for (var i = 0; i < this._onPreLoad.length; i++) { this._onPreLoad[i](); }
}
page.onresize = function(fn) {
    if (!inArray(fn, this._onReSize)) {
        this._onReSize[this._onReSize.length] = fn;
    }
};
page.resize = function() {
    if (this._onReSize.length == 0) {
        return;
    }
    for (var i = 0; i < this._onReSize.length; i++) { this._onReSize[i](); }
}


function _findInput(id) {
    return $("[id$=" + id + "]").eq(0);
}



function padLeft(text, len, chr) {
    while (text.length < len) {
        text = chr + text;
    }
    return text;
}



function toInt(num) {
    return parseInt(num, 10);
}



function setPageId(id) {
	pageId = id;
}

function debugObject(o) {
    var s = "";
    for (i in s) {
        s += i +"=" + o[i] + ", ";
    }
    return s;
} 

function preloadImages(imagesArray, directory) {
    path = ROOT_URL + "images/" + directory;
    for (i=0; i<imagesArray.length; i++) {
	    var cImg = new Image();
	    cImg.src = path + imagesArray[i];
    }
}



function toggleImage(el) {
	el.src = (el.src.indexOf(".on.gif") > -1) ? el.src.replace(".on.gif", ".gif") : el.src.replace(".gif", ".on.gif");
}

function toggleCurrency(el) {
    el.className = el.className == "hilight" ? "" : "hilight";	
}

function getEl(id) {
	return document.getElementById(id);
}

function popupWindow(url, width, height, extra) {
	specs = "width="+width+",height="+height+",toolbar=0,scrollbars=0,resizable=1";
	if (extra != null) {
		specs += "," + extra;
	}
	var puw = window.open(url, "PopUpWindow",  specs);
	if (puw != null) {
		puw.focus();
		return false;
	} 
	alert("Your browser has blocked a pop-up window");
	return true;
}


function hpFlashObject(swfFile, w, h, configXml) {
    var flashVars = "config=" + configXml;
    var flash = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"" + w + "\" height=\"" + h + "\" align=\"middle\">";
    flash += "<param name=\"movie\" value=\"" + swfFile + "\">";
    flash += "<param name=\"flashvars\" value=\"" + flashVars + "\">";
    //flash += "<param name=\"bgcolor\" value=\"#fff\">";
    flash += "<param name=\"wmode\" value=\"transparent\" />";
    flash += "<param name=\"allowscriptaccess\" value=\"samedomain\">";
    flash += "<param name=\"quality\" value=\"high\">";
    flash += "<embed flashvars=\"" + flashVars + "\" src=\"" + swfFile + "\" quality=\"high\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" width=\"" + w + "\" height=\"" + h + "\" align=\"middle\" allowscriptaccess=\"samedDomain\" wmode=\"transparent\">";
    flash += "</embed>";
    flash += "</object>";
    document.write(flash);
    //document.write("<textarea>" + flash + "</textarea>");
} 



/* FAQs */
var currentFaqCategory = "";
function selectFaqCategory(ddl) {  
    if (currentFaqCategory != "") {
        $("#" + currentFaqCategory).hide();
    }
    currentFaqCategory = "c" + ddl.selectedIndex + "c";
    if ($(currentFaqCategory) == null) {
        //alert(currentFaqCategory + "is null"); 
        return;
    }
    $("#" + currentFaqCategory).show();
}



function checkCookies() {
    redirectUrl = ROOT_URL + "help/cookies.aspx";
    //Create a Test cookie.
    var testcookie = 'jscookietest=valid';
    // Add this cookie in the cookie in the cookies collection of the document object.
    document.cookie = testcookie;
    if (document.cookie.indexOf(testcookie) == -1) {
		window.location.href = redirectUrl;
        return false;
    }
    return true;
}

/* Product Details */
function swapImage(imageId, src, nopreload) {
	if (browserAgent.indexOf("safari") > -1 || nopreload != null) {
		getEl(imageId).src = src;
		return;
	}
	try {
		var preloadImage = new Image();
		//getEl(imageId).src = "../images/loading.gif";
		preloadImage.onload = function() {
			getEl(imageId).src = src; //this.src;
		}
		preloadImage.src = src;
	} catch (ex) {
		getEl(imageId).src = src;
	}
}




/* Forms */
function getSelectValue(el) {
    return el == null ? "" : el.options[el.selectedIndex].value;
}
function getSelectText(el) {
    return el.options[el.selectedIndex].text;
}

function trimSpaces(el) {
	el.value = el.value.replace(/\s/g, "");
}		
function addFieldRestrictions(elId) {
	nospaces($(elId));
}
function nospaces(el) {
    if (el == null) {
		return;
	}
	el.onblur = function() {
		//trimSpaces(this);
	}
	el.onkeypress = function(e) {
	    if (!e) {
	        var e = window.event;
	    }
	    var remove = false;
	    //var _code;

	    if (e.keyCode) {
	        //_code = e.keyCode;
	        if (e.keyCode == 32) {
	            remove = true;
	        }
	    } else if (e.which) {
	        //_code = e.which;
	        if (e.which == 32) {
	            remove = true;
	        }
	    }

	    return !(remove);
	}
}

function centerElement(el) {
    $(el).center(true);
//	var pageSize = document.viewport.getDimensions();
//	var emSize = el.getDimensions();
//	var scrollPos = document.viewport.getScrollOffsets();
//	var x = Math.round(pageSize.width/2) - (emSize.width /2) + scrollPos.left;
//	var y = Math.round(pageSize.height/2) - (emSize.height /2) + scrollPos.top;	
//	el.style.position = "absolute";
//	el.style.left = x+'px';
//	el.style.top = y+'px';
}


function _hoverOver(value, ddl, text) {
    ddl = $("#" + ddl)[0];
    try {
        $("#" + text).html(ddl.options[(value-1)].text);
    } catch (ex) {
        //alert(value);
    }
}

function _hoverOut(value, ddl, text) {
    _hoverOver(ddl, text); 
}

function writeout(ddl, text) {
    try {
        ddl = $("#" + ddl);
        $("#" + text).html(ddl.options[ddl.selectedIndex].text);
    } catch (ex) {
        //alert(ddl + " - " + text);
    }
}

function submitOrder(el) {
    $("#dialog-submit").center(true).show();
    el.style.display = "none";
}


function blurLinks() {
    $("a,input[type=image]").focus(function() {
        if (this.blur) {
            this.blur(); 
        }
    });
}

/* preload product frames */
page.onload(function() {
    preloadImages(["large.png", "medium.png", "thumb.60x77.png", "small.png", "thumb.120x120.png", "thumb.120x154.png", "thumb.60x60.png"], "products/frames/");
    preloadImages(["popup.shadow.png", "popup.shadow.big.png"], "pageelements/");
});

page.onload(blurLinks);






/* START applesearch object */
if (!applesearch) var applesearch = {};

applesearch.init = function() {
    ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('opera') > -1) {
        $(document.body).addClass("opera");
    } else if (ua.indexOf('applewebkit') > -1 && (ua.indexOf('chrome') == -1 && ua.indexOf('iron') == -1)) {
//        $("#applesearch").addClass("safari"); //should add to body?
//        $("#srch_fld").attr("placeholder", "");
//        $("#srch_fld").attr("autosave", "bsn_srch");
//        $("#srch_fld").attr("results", "5");
//        //$("srch_fld").size = "100";
//        $("#srch_fld").type = "search";

//        if ($("#qsearch").length > 0) {
//            $("#quicksearch").addClass("safari");
//            $("#qsearch").attr("placeholder", "");
//            $("#qsearch").attr("autosave", "bsn_srch");
//            $("#qsearch").attr("results", "5");
//            $("#qsearch").css("width", "100%");
//            $("#qsearch").attr("type", "search");
//        }

//        if ($("#ptabs").length > 0) {
//            $("#ptabs").addClass("safari");
//        }
    }
}

// called when on user input - toggles clear fld btn
applesearch.onChange = function(fldID, btnID) {
    // check whether to show delete button
    var fld = $.$(fldID);
    var btn = $.$(btnID);
    if (fld.value.length > 0 && !this.clearBtn) {
        btn.className = "sbox_r2";
        //btn.style.background = "transparent url('/images/pageelements/srch_r_f2.gif') no-repeat top left";
        btn.fldID = fldID; // btn remembers it's field
        btn.onclick = this.clearBtnClick;
        this.clearBtn = true;
    } else if (fld.value.length == 0 && this.clearBtn) {
        //btn.style.background = "transparent url('/images/pageelements/srch_r.gif') no-repeat top left";
        btn.className = "sbox_r";
        btn.onclick = null;
        this.clearBtn = false;
    }
}


// clears field
applesearch.clearFld = function(fldID, btnID) {
    var fld = $.$(fldID);
    fld.value = "";
    this.onChange(fldID, btnID);
}

// called by btn.onclick event handler - calls clearFld for this button
applesearch.clearBtnClick = function() {
    applesearch.clearFld(this.fldID, this.id);
}

/* END applesearch object */
page.onload(applesearch.init)


page.onload(function() {
    $(".noautocomplete").attr("autocomplete", "off");
});





$(function() {
    //window.onload = function() {
    //$(document).ready(function() {
    page.preload();
    page.load();
    page.resize();
    //}
});

window.onresize = function() {
    page.resize();
}



function parseXmlResponse(xmldoc) {
    var ret = new Object();
    var isMSIE = browserAgent.toLowerCase().indexOf("msie") > -1;
    var _html = $(xmldoc).find("html")[0];
    ret.html = isMSIE ? _html.childNodes[0].text : _html.textContent;

    try {
        var _script = $(xmldoc).find("script")[0];
        ret.script = isMSIE ? _script.childNodes[0].text : _script.textContent;
    } catch (ex) {
    }
    return ret;
}

/* TOOL TIPS */
function showToolTip(el, id, cssClass) {
    var position = $(el).position();
    var newX = (position.left + 200) > document.body.clientWidth ? position.left - 200 : position.left;
    $.$(id).style.left = newX + "px";
    $.$(id).style.top = (position.top + 20) + "px";
    $.$(id).className = cssClass == null ? "showTooltip" : cssClass;
}

function showInlineToolTip(el, id) {
    showToolTip(el, id, "showInlineTooltip");
}

function hideToolTip(id) {
    $.$(id).className = "tooltip";
}


//var mouseX = 0;
//var mouseY = 0;
//$().mousemove(function(e) {
//    mouseX = e.pageX;
//    mouseY = e.pageY;
//});



/* LOGIN PAGE */
var logincontrol = {};

logincontrol.passwordReminder = function(email) {
    if (email.length == 0) {
        alert("You must enter your email address");
        return false;
    }
    var _url = ROOT_URL + "webservices/passwordreminder.aspx?email=" + email;
    $.get(_url, function(data) {
        logincontrol.passwordReminderConfirmation(parseXmlResponse(data));
    });
    return false;
}

logincontrol.passwordReminderConfirmation = function(response) {
    $("#addtobasket").center(true).show();
    $("#addtobasketresult").html(response.html).show();
    try {
        if (response.script.length > 0) {
            eval(response.script);
        }
    } catch (ex) {
    }
    setTimeout(function() {
        $("#addtobasket").pause("5000").fadeOut();
    }, 10000);
    //$("#addtobasket").pause("10000").fadeOut();
}

logincontrol.closeDialog = function() {
    $("#addtobasket").hide();
}

/* REGISTRATION PAGE */
var registrationpage = {};
registrationpage.init = function(pageId) {
    setPageId(pageId);
    bindHowHeard();
    //$("field-email").each(function() { addFieldRestrictions(this); });
    $.$("addressTable").className = $(":hidden", $(".hf")).val();
    initAddressLookup();

    $(".submit-button").click(function() {
        $(":hidden", $(".hf")).val($.$("addressTable").className);
    });
    //    document.forms[0].onsubmit = function() {
    //        $(":hidden", $("hf")).val($.$("addressTable").className);
    //    }

}

/* CHECKOUT - DELIVERY PAGE */
var deliverypage = {};
deliverypage.showDeliveryAddressChoices = function() {
    $("#selectDelAddr").center(true).show();
    document.body.className = "noselects";
    return false;

}
deliverypage.hideDeliveryAddressChoices = function() {
    $("#selectDelAddr").hide();
    document.body.className = "";
    return false;
}

/* CHECKOUT - PAYMENT PAGE */
// Following code is used to jump from one box to the next
function nextBox(input, len, e) {
    var isNN = (navigator.appName.indexOf("Netscape") != -1);
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
    if (input.value.length >= len && $.inArray(keyCode, filter) == -1) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input) + 1) % input.form.length].focus();
    }
    function getIndex(input) {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
            if (input.form[i] == input) index = i;
        else i++;
        return index;
    }
    return true;
}	