// File: global.js
// Requires: prototype.js

// ****************************************** Global Proceedures *********************************************

function translateAjaxResponse(response) {
    var jsonResp = null;
    if (response && typeof(response.responseText) != "undefined" && response.responseText) {
        var json = eval('(' + response.responseText + ')');
        jsonResp = (json && typeof(json.response) == "object" ? json.response : null);
    }
    return jsonResp;
}

function getEltOffsetPos(elt, eltAncestor) {
    var offLeft = elt.offsetLeft, offTop = elt.offsetTop;
    if (eltAncestor) {
        var eltCurr = elt;
        while ((eltCurr = eltCurr.offsetParent) != null && eltCurr != eltAncestor) {// && eltCurr != document
            offLeft += eltCurr.offsetLeft;
            offTop += eltCurr.offsetTop;
        }
    }
    return {left : offLeft, top: offTop};
}

function detectJavaScriptSupportChange() {
    var change = false;
    // safely check for the nojs cookie.  remove if it's found.
    // depends on cookie.js
    if (typeof(cookieReader) == "function" && typeof(createCookie) == "function") {
        var nojscookiename = "nojs";
        if (cookieReader(nojscookiename) != null) {
            createCookie(nojscookiename, "", -1);
            change = true;
        }
    }
    // save the state in the photobucket obj
    if (photobucket) {
        photobucket.jsSupportChanged = change;
    }
}
// delay call so cookie.js can load
Event.observe(window, "load", detectJavaScriptSupportChange);

var set_useragent_classes;
if (set_useragent_classes) jq(document).ready(function() {
    var b = jq(document.body);
    if (photobucket.browser.isIE) b.addClass("is_ie");
    if (photobucket.browser.isIE6) b.addClass("is_ie6");
    if (photobucket.browser.isIE7) b.addClass("is_ie7");
    if (photobucket.browser.isIE8) b.addClass("is_ie8");
    if (photobucket.browser.isSafari) b.addClass("is_saf");
    if (photobucket.browser.isFirefox) b.addClass("is_moz");
});


/* Static object for global definitions */
var photobucket = {
    browser: {
        isIE: (navigator.userAgent.indexOf("MSIE") != -1),
        isIE6: (navigator.userAgent.indexOf("MSIE 6") != -1),
        isIE7: (navigator.userAgent.indexOf("MSIE 7") != -1),
        isIE8: (navigator.userAgent.indexOf("MSIE 8") != -1),
        isIE9: (navigator.userAgent.indexOf("MSIE 9") != -1),
        isSafari: (navigator.userAgent.indexOf("AppleWebKit") != -1),
        isFirefox: (navigator.userAgent.indexOf("Firefox") != -1),
        isOpera: (navigator.userAgent.indexOf("Opera") != -1)
    },

    ui: {

        // -----------------------------------------------------------------------------------
        //
        // getPageScroll()
        // Returns object with x,y page scroll values.
        // Core code from - quirksmode.org
        //
        getPageScroll: function() {
            var yScroll;
            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop){     // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
            } else if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
            }

            pageScrollObj = {
                'xScroll': null,
                'yScroll': yScroll
            };
            return pageScrollObj;
        },

        // -----------------------------------------------------------------------------------
        //
        // getPageSize()
        // Returns object with page width, height and window width, height
        // Core code from - quirksmode.org
        // Edit for Firefox by pHaez
        //
        getPageSize: function() {
            var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {
                xScroll = document.body.scrollWidth;
                yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }

            var windowWidth, windowHeight;
            if (self.innerHeight) {    // all except Explorer
                windowWidth = self.innerWidth;
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }

            // for small pages with total height less then height of the viewport
            if (yScroll < windowHeight) {
                pageHeight = windowHeight;
            } else {
                pageHeight = yScroll;
            }

            // for small pages with total width less then width of the viewport
            if (xScroll < windowWidth) {
                pageWidth = windowWidth;
            } else {
                pageWidth = xScroll;
            }

            pageSizeObj = {
                'pageWidth': pageWidth,
                'pageHeight': pageHeight,
                'windowWidth': windowWidth,
                'windowHeight': windowHeight

            };
            return pageSizeObj;
        },

        scrollTo: function(url, speed, easing, redirect) {
            url = url || "#";
            speed = speed || "fast";
            easing = easing || null;
            redirect = (redirect === true || redirect == null) ? true : false;

            if (url) {
                if (url.indexOf("#") != -1) {
                    var aParts = url.split("#",2);
                    var anchor = jq("a[name='"+aParts[1]+"']");
                    if (anchor) {
                        if (jq(document).height()-anchor.offset().top >= jq(window).height()
                           || anchor.offset().top > jq(window).height()
                           || jq(document).width()-anchor.offset().left >= jq(window).width()
                           || anchor.offset().left > jq(window).width()) {

                            jq('html, body').animate({
                                scrollTop: anchor.offset().top,
                                scrollLeft: anchor.offset().left
                            }, speed, easing, function(){
                                if (redirect) {
                                    window.location = url
                                }
                            });
                        }
                        return false;
                    }
                }
            }
        },
        
        setButtonDisabled: function(eltBttn, bDisabled) {
            if (eltBttn) {
                eltBttn.disabled = bDisabled;
                if (bDisabled) {
                    Element.addClassName(eltBttn, "disabled");
                } else {
                    Element.removeClassName(eltBttn, "disabled");
                }
            }
        },

        loadScript: function(url) {
            var e = document.createElement("script");
            e.src = url;
            e.type="text/javascript";
            document.getElementsByTagName("head")[0].appendChild(e);
        }
    }
};

function cookieReader(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return '';
}

function compoundCookieReader(name, key) {
    var coookie = cookieReader(name);
    if (coookie == '') return '';
    if (coookie.indexOf(key)==-1)  return '';
    var cookiearray =  coookie.split(escape("|"));
    for (var i=0;i<cookiearray.length; i++) {
        var c = cookiearray[i];
        if(c.indexOf(key)>-1) {
            var va = c.split(escape("="));
            return va[1];
        }
    }
}

function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    document.cookie = name+"="+escape(value)+expires+"; path=/; domain= .photobucket.com";
}

function createCompoundCookie(name,key,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    if (days == 0) expires = "";
    var cookiestr = key+escape("=")+escape(value);
    var coookie = cookieReader(name);
    var oldvalue = compoundCookieReader(name,key);
    if (coookie!='' && oldvalue !='') {
        coookie = coookie.replace(key+escape("=")+oldvalue, cookiestr);
    }
    if (coookie!='' && oldvalue ==''){
        coookie += escape("|")+cookiestr;
    }
    if (coookie == "") coookie = cookiestr;
    document.cookie = name+"="+coookie+expires+"; path=/; domain= .photobucket.com";
}

function createCookieByUnixTimestamp(name,value,unixTime) {
    var expires = "";
    if (unixTime) {
        var objdate = new Date();
        objdate.setTime(unixTime*1000);// Convert PHP Unix Epoch (secs) to UTC time (milliseconds)
        expires = "; expires="+objdate.toGMTString();
    }
    document.cookie = name+"="+escape(value)+expires+"; path=/; domain= .photobucket.com";
}

function disableTextHighlight(elem) {
    if (typeof(elem.onselectstart)!="undefined")
        elem.onselectstart=function(){return false}
    else if (typeof(elem.style.MozUserSelect)!="undefined")
        elem.style.MozUserSelect="none"
    else
        elem.onmousedown=function(){return false}

    elem.style.cursor = "default"
}

String.prototype.alphaonly = function() {
        return this.replace('&amp;', 'and').replace('&', 'and').replace(/[^a-zA-Z0-9\s]/g, '');
}

// Share manager
var pb_share_manager = {
    hasJsLoaded: false,
    shareJSArray: ['share/sharePanel',
                   'share/panel/easypost',
                   'share/panel/emailshare',
                   'share/panel/links',
                   'contacts/contactmanager',
                   'common/util/autocompleteBase',
                   'common/util/autocompleteEmail'],

    loadShareJs: function() {
        var head = document.getElementsByTagName('head');
        
        // load the share package if defined (in production)
        if (pb_sharepkg != '') {
            var url = pb_staticServer+'/include/js/pkgs/'+pb_version+'/share.js';
            var e = document.createElement('script');
            e.async = false;
            e.setAttribute("type","text/javascript");
            e.src = url;
            head[0].appendChild(e);
        } else { // load each js file for share package individually
            for (var i=0;i<this.shareJSArray.length;i++) {
                var e = document.createElement('script');
                e.async = false;

                if (pb_version == '') {
                    var url = pb_staticServer+'/include/js/'+this.shareJSArray[i]+'.js';
                } else {
                    var url = pb_staticServer+'/include/js/'+this.shareJSArray[i]+'_v'+pb_version+'.js';
                }
                e.setAttribute("type","text/javascript");
                e.src = url;
                head[0].appendChild(e);
            }
        }
        
        this.hasJsLoaded = true;
    },
    getSharePanel: function(memo) {
        document.fire(PBLightbox.PBProgress.EVENT.ACTIVATE);
        if (!this.hasJsLoaded) {
            this.loadShareJs();
        }
        
        var paramStr = '';
        for (var n in memo) {
            paramStr += n+',';
        }
        
        var params = jq.param(memo);
        params += '&paramstr='+paramStr;
        
        document.fire(PBLightbox.EVENT.ACTIVATE, {
            contentUrl: '/getsharepanel/?'+params,
            cache: false
        });
    }
};

