// TemplateControl javascript - must be included on any page that uses TemplateControl web control.
var ua = navigator.userAgent.toLowerCase();
var RootUrl;
var isPrint = false;
var useIEPngHack = ( ((ua.indexOf("msie 5") != -1) || (ua.indexOf("msie 6") != -1)) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));

/*
 * Utility functions
 */

function debug(str) {
	//alert(str);
	//t = document.getElementById('debuglog'); if (t != null) t.value = t.value + str + '\n';
}

function fncall(str) {
	//debug(str);
}

// Get Element By Id
function gebi(id) {
	fncall('gebi ' + id);
	return document.getElementById(id);
}

function getSize(element) {
	fncall('getSize ' + element.id);
	return new Dimension(element.width, element.height);
}

// can be used to call multiple functions upon page load
function addLoadEvent(func) 
{   
  var oldonload = window.onload;   
  if (typeof window.onload != 'function') {   
    window.onload = func;   
  } else {   
    window.onload = function() {   
      if (oldonload) {   
        oldonload();   
      }   
       func();   
     };
   }   
} 

//Test if a string ends with another string
function endsWith(testString, endingString){
      if(endingString.length > testString.length) return false;
      return testString.indexOf(endingString)==(testString.length-endingString.length);
} 
//Returns a query string value
function querySt(a) 
{
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) 
{
   ft = gy[i].split("=");
   if (ft[0] == a) {
   return ft[1];
}
}
}

//*************************************
//* Web Service / PageMethod callbacks
//*************************************
function gotError(error, ctx, methodName) {
    if (error) {
        //var errMsg = error.get_message();
        //var stkTrace = error.get_stackTrace();
        //var errType = error.get_exceptionType(); 
        var errStatus = error.get_statusCode();
        //var errTimedOut = error.get_timedOut();
        // IE http://support.microsoft.com/default.aspx?scid=kb;EN-US;193625
        switch (errStatus) {
            case 12002: // IE The request has timed out.
                {
                    // ignore                
                    break;
                }
            case 12030: // IE The connection with the server has been terminated.
            case 12031: // IE The connection with the server has been reset.            
            case 401:   // HTTP 401 Unauthorized
                {
                    alert("Authentication Failed. Please click OK to proceed to login page.");
                    document.location = RootUrl;
                    break;
                }
            default:
                {
                    var nl = "\r\n";
                    var message =
                "Method Name: " + methodName + nl + nl +
                "Status Code: " + error.get_statusCode() + nl + nl +
                "Error: " + error.get_message() + nl + nl +
                "Exception Type: " + error.get_exceptionType() + nl + nl +
                "Stack Trace: " + error.get_stackTrace() + nl;

                    try {
                        var mService = new IMasterService;
                        mService.LogError(message, Redirect, gotError);
                    }
                    catch (e) {
                        document.location = RootUrl + "error.aspx";
                    }

                    //alert(message);       
                    //alert('{"Message":"'+errMsg+'","StackTrace":"'+stkTrace+'","ExceptionType":"'+errType+'","MethodName":"'+methodName+'","StatusCode":"'+errStatus+'","TimeOut":"'+errTimedOut+'"}'); 
                    //document.location = RootUrl+"error.aspx";
                    break;
                }
        }
    }
    if (typeof hideLoadingPopup == "function")
        hideLoadingPopup();
} 
function gotSuccess(result) { // dummy callback function for service call that doesn't need to do anything on success. We need this so we can utilize the error callback function.
}

function gotRedirect(result)
{
    if (result)
    {
        location.href = result;
    }
}

function Redirect(result) {
    if (result) {
        location.href=RootUrl+result;
    }
}


function resize(element, w, h) {
	w = Math.max(0, w);
	h = Math.max(0, h);
	fncall('resize ' + element.id + ' ' + w + ' ' + h);
	element.style.width = w + 'px';
	element.style.height = h + 'px';
}

function move(element, x, y) {
	fncall('move ' + element.id + ' ' + x + ' ' + y);
	element.style.top = '' + y + 'px';
	element.style.left = '' + x + 'px';
}

function setLeft(o,v)	{if(o)o.style.left=v+"px";}
function setTop(o,v)	{if(o)o.style.top=v+"px";}

function getLeft(o)		{if(!o||(!o.style)||(!o.style.left))  return 0; return parseInt(o.style.left.replace("px",""));}
function getTop(o)		{if(!o||(!o.style)||(!o.style.top))  return 0; return parseInt(o.style.top.replace("px",""));}
function getWidth(o)	{if(!o||(!o.style)||(!o.style.width)) return 0; return parseInt(o.style.width.replace("px",""));}
function getHeight(o)	{if(!o||(!o.style)||(!o.style.height))return 0; return parseInt(o.style.height.replace("px",""));}
function getPosition(o) {return new Point( getLeft(o), getTop(o));}

function clip(element, rect) {
	fncall('clip ' + element.id + ' ' + rect.x + ' ' + rect.y + ' ' + rect.w + ' ' + rect.h);
	var l = (rect.x);
	var r = (rect.x + rect.w);
	var t = (rect.y);
	var b = (rect.y + rect.h);
	element.style.clip = 'rect(' + t + 'px, ' + r + 'px, ' + b + 'px, ' + l + 'px)';
}

// Returns a new Dimension scaled as requested
function scale(originalDim, requestedDim, crop) {
	fncall('scale ' + originalDim + ' ' + requestedDim + ' ' + crop);
	if(!requestedDim && originalDim) return originalDim;
	var outAspect = requestedDim.w / requestedDim.h;
	var imgAspect = originalDim.w / originalDim.h;
	if (imgAspect < outAspect == crop) {
		// Scale to max width
		return new Dimension(requestedDim.w, requestedDim.w / imgAspect);
	}
	else {
		// Scale to max height
		return new Dimension(requestedDim.h * imgAspect, requestedDim.h);
	}
}

// Utilities functions
if(typeof String.prototype.endsWith == "undefined"){
    String.prototype.endsWith = function(s){
        var s_i = this.lastIndexOf(s);
        return (s_i < 0)?false:(this.substring(s_i)===s);
    }
}
function AttachEvt(element, eventName, method){
	if(element.attachEvent){ eventName="on"+eventName;element.attachEvent(eventName,method);	}
	else{ element.addEventListener(eventName,method,true); }
}
function cancelBbl(evt){
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    } else if (evt.cancelBubble) {
        evt.cancelBubble = true;
        evt.returnValue = false;
    }
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return {x:curleft,y:curtop};
}
function scrollX(){
    return ((document.all)?document.documentElement.scrollLeft:window.pageXOffset);
}
function scrollY(){
    return ((document.all)?document.documentElement.scrollTop:window.pageYOffset);
}
function getDim(element) {
	return new Dimension((element.offsetWidth||element.width), (element.offsetHeight||element.height));
}
/*
 * Classes
 */

// Rectangle can be passed around as Dimension and Point also (duck typing)
function Rectangle(x, y, w, h) {
	this.x = isNaN(x)?0:x;
	this.y = isNaN(y)?0:y;
	this.w = isNaN(w)?0:w;
	this.h = isNaN(h)?0:h;
}
Rectangle.prototype.toString = function(){
	return "Rectangle{ x:"+this.x+", y:"+this.y+", w:"+this.w+", h:"+this.h+" }"
}
function Dimension(w, h) {
	this.w = isNaN(w)?0:w;
	this.h = isNaN(h)?0:h;
}
Dimension.prototype.toString = function(){
	return "Dimension{ w:"+this.w+", h:"+this.h+" }"
}
function Point(x, y) {
	this.x = isNaN(x)?0:x;
	this.y = isNaN(y)?0:y;
}
Point.prototype.toString = function(){
	return "Point{ x:"+this.x+", y:"+this.y+" }"
}
// firefox click() method fix
if(typeof HTMLElement == "function"){
	HTMLElement.prototype.click = function() { 
		var evt = this.ownerDocument.createEvent('MouseEvents');
		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		this.dispatchEvent(evt);
	}
}
function openHelpPopup(page) {
    var w = 805;
    var h = 580;
    var winl = (screen.width-w)/2;
    var wint = (screen.height-h)/2;
    var settings ='height='+h+',';
    settings +='width='+w+',';
    settings +='top='+wint+',';
    settings +='left='+winl+',';
    settings +='scrollbars=no,';
    settings +='resizable=no,';
    settings +='toolbar=no,';
    settings+='status=no,';
    settings+='menubar=no,';
    settings += 'titlebar=no,';
    settings+='location=no';
    childWindow=window.open(page,'location',settings);
    if(childWindow != null)
        childWindow.window.focus();			
}

function BrowserIsFirefox()
{
    return (navigator.userAgent.indexOf("Firefox")!=-1);
}

function BrowserIsIE()
{
    return (navigator.appVersion.indexOf("MSIE")!=-1);
}

function BrowserIsIE6()
{
    var isIE6 = false;
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) //test for MSIE x.x;
    { 
        var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        
        if ((ieversion>=6) && (ieversion<7))
            isIE6 = true;
    }
    return isIE6;
}

function BrowserIsIE7()
{
    var agent  = navigator.userAgent.toLowerCase();
    var is_ie  = ((agent.indexOf("msie") != -1) && (agent.indexOf("opera") == -1));
    var is_ie7 = (is_ie && agent.indexOf("msie 7.0") != -1);
    return is_ie7;
}

function BrowserIsFirefox2()
{
    // source: http://www.javascriptkit.com/javatutors/navigator.shtml
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
    { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ffversion>=3)
            return false;
        else
            return true;
    }
    return false;
}

function BrowserIsFirefox3()
{
    // source: http://www.javascriptkit.com/javatutors/navigator.shtml
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
    { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ffversion>=3)
            return true;
        else
            return false;
    }
    return false;
}

function OSIsVista()
{
    if (navigator.userAgent.indexOf("windows NT 6.0") > -1)
        return true;
    else
        return false;
}

function BrowserIsSafari()
{
    return (navigator.userAgent.indexOf("Safari")!=-1);
}

function unselectText() {
    if (window.getSelection) {
        window.getSelection().removeAllRanges();
    } else if (document.selection) {
        document.selection.empty();
    }
}

function RemoveAllChildNodes(container)
{
    if (container.hasChildNodes())
    {
        while (container.childNodes.length >= 1)
        {
            container.removeChild(container.firstChild);
        }
    }
}

function ImagePreloader()
{
    this.images = new Array;
}

ImagePreloader.prototype = {
    images:null,
    
    Load: function(imageUrl, callbackFunction, context)
    {
        return this.LoadEx(imageUrl, callbackFunction, null, context);
    },
    
    LoadEx: function(imageUrl, callbackFunction, callbackErrorFunction, context)
    {
        var oImage = new Image;
        
        oImage.oLoader = this;
        oImage.oLoaded = false;
        oImage.oContext = context;
        oImage.oCallback = callbackFunction;
        oImage.oCallbackError = callbackErrorFunction;
        oImage.onload  = ImagePreloader.prototype.onload;
        oImage.onerror = ImagePreloader.prototype.onerror;
        oImage.onabort = ImagePreloader.prototype.onerror;
        
        oImage.src = imageUrl;
        
        this.images.push(oImage);
        
        if (oImage.complete)
        {
            oImage.onload();
        }
        
        return oImage;
    },
    
    onload: function()
    {
        if (this.oLoaded)
        {
            return;
        }
        if (typeof(this.oCallback) != 'undefined' && this.oCallback != null)
        {
            this.oLoaded = true;
            this.oCallback(this.oContext);
        }
    },
    
    onerror: function()
    {
        if (typeof(this.oCallbackError) != 'undefined' && this.oCallbackError != null)
        {
            this.oCallbackError(this.oContext);
        }
    }
    
};

var ImageLoader = new ImagePreloader();

function RadixSortAlgorithm()
{
}

RadixSortAlgorithm.prototype = {

    _sortDigit: function(k, dig)
    {
        return dig < k.length ? k.charCodeAt(k.length - 1 - dig) : 255;
    },

    _sortPass: function(a, N, dig)
    {
        var counter = new Array(256);
        var temp = new Array();
        var i, d;

        for (d = 0; d <= 256; d++)
        {
            counter[d] = 0;
        }
        for (i = 1; i <= N; i++)
        {
            counter[this._sortDigit(a[i].Key, dig)]++;
        }
        for (d = 1; d <= 256; d++)
        {
            counter[d] += counter[d-1];
        }
        for (i = N; i >= 1; i--)
        {
            temp[counter[this._sortDigit(a[i].Key, dig)]--] = a[i];
        }

        for (i = 1; i <= N; i++)
        {
            a[i] = temp[i];
        }
    },
    
    _sort: function(sortArray, sortPasses)
    {
        var N = sortArray.length - 1;
        for (var i = 0; i < sortPasses; i++)
        {
            this._sortPass(sortArray, N, i);
        }
    },
    
    _expandKeys: function(arrayToSort, sortPasses)      // TODO: Shouldn't need...
    {
        for (var i = 1; i < arrayToSort.length; i++)
        {
            var key = arrayToSort[i].Key;
            while (key.length < sortPasses)
            {
                key += ' ';
            }
            arrayToSort[i].Key = key;
        }
    },
    
    sortByKey: function(arrayToSort, sortBy)
    {
        var sortArray = new Array;
        var sortPasses = 0;
        
        sortArray.push(null);
        
        for (var i = 0; i < arrayToSort.length; i++)
        {
            var sortKey = arrayToSort[i][sortBy].toLowerCase();
            
            sortArray.push({ Key: sortKey, Value: arrayToSort[i] });
            
            sortPasses = Math.max(sortPasses, sortKey.length);
        }
        
        this._expandKeys(sortArray, sortPasses);
        this._sort(sortArray, sortPasses);
        
        for (var i = 1; i <= arrayToSort.length; i++)
        {
            arrayToSort[i - 1] = sortArray[i].Value;
        }
    },
    
    sortByKeyCallback: function(arrayToSort, getSortKeyCallback)
    {
        var sortArray = new Array;
        var sortPasses = 0;
        
        sortArray.push(null);
        
        for (var i = 0; i < arrayToSort.length; i++)
        {
            var sortKey = getSortKeyCallback(arrayToSort[i]).toLowerCase();
            
            sortArray.push({ Key: sortKey, Value: arrayToSort[i] });
            
            sortPasses = Math.max(sortPasses, sortKey.length);
        }
        
        this._expandKeys(sortArray, sortPasses);
        this._sort(sortArray, sortPasses);
        
        for (var i = 1; i <= arrayToSort.length; i++)
        {
            arrayToSort[i - 1] = sortArray[i].Value;
        }
    }

};

var RadixSort = new RadixSortAlgorithm();


function NewWindow(mypage,myname,w,h,scroll,resizable)
{
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	var settings ='height='+h+',';
	settings +='width='+w+',';
	settings +='top='+wint+',';
	settings +='left='+winl+',';
	settings +='scrollbars='+scroll+',';
	settings +='resizable=no';
	childWindow=window.open(mypage,myname,settings);
	childWindow.window.focus();
}

//
// Popup
//

Type.registerNamespace('PhotoSite');
PhotoSite.Popup = function (clientID)
{
    this._clientID = clientID;
}

PhotoSite.Popup.prototype = {
    _clientID: null,
    
    show: function()
    {
        showPopup(this._clientID);
    },
    
    hide: function()
    {
        hidePopup(this._clientID);
    }
};

function showPopup(popupID)
{
    if (popupID)
    {
        var fullPopupID = popupID + "_mpePopup";
        var popup = $find(fullPopupID);
        if(popup)
            popup.show();
    }
}

function hidePopup(popupID)
{
    if (popupID)
    {
        var fullPopupID = popupID + "_mpePopup";
        var popup = $find(fullPopupID);
        if(popup)
            popup.hide();
    }
}

//
// String Resource...
//
PhotoSite.StringResource = function()
{
}
PhotoSite.StringResource.prototype.add = function(strings)
{
    for (var key in strings)
    {
        this[key] = strings[key];
    }
}
var SR = new PhotoSite.StringResource();

//
// Header menu navigation
//

var menuCaptionOver = false;
var menuContentOver = false;
var menuVisible = false;

function onMenuCaptionOver()
{
    menuCaptionOver = true;
    showMenuDiv();
}

function onMenuContentOver()
{
    menuContentOver = true;
    showMenuDiv();
}

function onMenuCaptionOut()
{
    menuCaptionOver = false;
    showMenuDiv();
}

function onMenuContentOut()
{
    menuContentOver = false;
    showMenuDiv();
}

function showMenuDiv()
{
    var show = menuCaptionOver || menuContentOver;
    
    if (show != menuVisible)
    {
        menuVisible = show;

        var subMenu = document.getElementById('div_submenu_container');
        
        subMenu.style.display = show ? '' : 'none';
        
        if (BrowserIsIE6())
        {
            if (show)
            {
                showHideDropDowns(false);
                clearTimeout(ie6_showDropDownTimeoutID);
            }
            else
            {
                ie6_showDropDownTimeoutID = setTimeout(function(){showHideDropDowns(true);}, 500);
            }
        }
    }
}

var ie6_dropDownsVisible = true;
var ie6_showDropDownTimeoutID = null;

function showHideDropDowns(show)
{
    if (ie6_dropDownsVisible == show)
    {
        return;
    }

    var allInputs = document.getElementsByTagName('select');
    
    for (var i = 0; i < allInputs.length; i++)
    {
        var sel = allInputs[i];
        
        if (sel.parentNode.tagName == 'SPAN') // hack for gifts selection filters...
        {
            sel.parentNode.style.visibility = show ? 'visible' : 'hidden';
        }
    }
    
    ie6_dropDownsVisible = show;
}

var lastActiveSubMenuId = '';

/*function showSubMenu(sender, eCategoryId, eProductPlacementId) 
{
    var subMenuId = "sub_cat_" + eCategoryId;
    var subMenuWrapper = document.getElementById('submenu');
    
    if ((lastActiveSubMenuId == subMenuId) && (subMenuWrapper && subMenuWrapper.style.display != 'none'))
    {
        return;
    }
     
    lastActiveSubMenuId = subMenuId;
    
    var subMenuBody = $get('div_subnav_body');
    var subMenuBodyContent = document.getElementById('div_subnav_body_content');
    var subMenu = document.getElementById(subMenuId);
    var categoryNameDiv = document.getElementById('div_category_id');
    
    categoryNameDiv.innerHTML = sender.innerHTML;     
    subMenuBodyContent.innerHTML = subMenu.innerHTML;
    subMenuBody.style.display = 'block';   

    var menuItemPos = findPos(sender);

    subMenuWrapper.style.left = (menuItemPos.x - 7) + 'px';
    subMenuWrapper.style.top = (menuItemPos.y - 7) + 'px';
    subMenuWrapper.style.visibility = "visible";
    subMenuWrapper.style.display = '';
    
    var caption = document.getElementById('subnav_caption_tab');
    var submenu = document.getElementById('div_subnav_body');

    caption.eCategoryId = eCategoryId;
    caption.eProductPlacementId = eProductPlacementId;
    caption.onclick = function() { UpdateNavigation(this.eCategoryId, this.eProductPlacementId, ''); }

    var width = caption.offsetWidth;

    caption.style.width = 'auto';
    submenu.style.width = 'auto';
    
    while (caption.offsetHeight > 30 && width < 200)
    {
        caption.style.width = width + 'px';
        width += 3;
    }
    
    if (submenu.offsetWidth < caption.offsetWidth)
    {
        submenu.style.width = (caption.offsetWidth - 2) + 'px';
    }
    
    var subItems = subMenu.childNodes.length;
    
    width = submenu.offsetWidth;
    
    while (submenu.offsetHeight > ((subItems * 22) + 15) && width < 200)
    {
        submenu.style.width = width + 'px';
        width += 10;
    }
}*/


function showSubMenu(sender, id) {

    var currentSubMenu = $get(id);
    var menuContainer = $get('div_submenu_container');
    var menuItemPos = findPos(sender);

    menuContainer.innerHTML = currentSubMenu.innerHTML;

    menuContainer.style.left = (menuItemPos.x + 7) + 'px';
    menuContainer.style.top = (menuItemPos.y + (BrowserIsIE() ? 36.5 : 35.5)) + 'px';
    menuContainer.style.visibility = "visible";
    menuContainer.style.display = '';
hideDomSortDropDown()
    menuVisible = true;
}

function hideSelect() {
    var browserInfo = navigator.userAgent.toLowerCase();
    if (browserInfo.indexOf("msie 6.0") > -1) {
        document.body.className += 'hideSelects';
    }
}

function showSelect() {
    var browserInfo = navigator.userAgent.toLowerCase();
    if (browserInfo.indexOf("msie 6.0") > -1) {
        document.body.className = document.body.className.replace('hideSelects', '');
    } 
}

function hideDomSortDropDown() {
    var browserInfo = navigator.userAgent.toLowerCase();
    if (browserInfo.indexOf("msie 6.0") > -1) {
        if (domSortDropDown == null)
            domSortDropDown = document.getElementById("ThumbHolder_domSortDropDown");

        if (domSortDropDown != null && typeof domSortDropDown != "undefined")
            domSortDropDown.parentNode.style.display = "none";
    }
        
}

function showDomSortDropDown() {
    var browserInfo = navigator.userAgent.toLowerCase();
    if (browserInfo.indexOf("msie 6.0") > -1) {
        if (domSortDropDown == null)
            domSortDropDown = document.getElementById("ThumbHolder_domSortDropDown");

        if (domSortDropDown != null && typeof domSortDropDown != "undefined")
            domSortDropDown.parentNode.style.display = "";
    }
}


function fileExists(url) {

    if (url == null || url.replace(/^\s+|\s+$/g, "") == "")
        return false;

    var oHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    try {
        oHttp.open("HEAD", url, false);
        oHttp.send(null);
    }
    catch (e) {
        var message = e.message.toLowerCase();
        if (message.match(/denied/) || typeof oHttp.status == 'unknown' || parseInt(e.number) == -2147024891)//file likely exists, but access is denied.
            return true;
    }

    return (oHttp.status == 404) ? false : true;
}

function getConcreteImageUrl(url) {

    if (fileExists(url))
        return url;
    else
        return "../images/no_image.gif";

}

function GetElementByPartialID(partialID, type) 
{
    var elements = document.getElementsByTagName(type);
    for (var i = 0; i < elements.length; i++) 
    {
        if (elements[i].id.indexOf(partialID) != -1) 
            return elements[i];
    }
}

function gotoUploadPage() {
    
    if (typeof displayType != 'undefined' && typeof ThumbHolder != 'undefined') {
        if (displayType == 'Album') {
            var albums = ThumbHolder.getSelectedItems();
            if (albums.length > 1)
                alert('Only one album can be selected.');
            else if (albums.length == 1)
                location.href = upload_photosUrl + '?a=' + albums[0].ID;
            else
                location.href = upload_photosUrl;
        }
        else
            location.href = upload_photosUrl;
    }
    else {
        location.href = upload_photosUrl;
    }
}
     
