// show the frames warning?
var framesWarning = true;

// filmStrip values you can override:
var rightMoves = 5;
var leftMoves = -5;

// how fast do you want the filmstrip to move?
var filmstripMove = 1;

// slideshow duration for each slide
var slideDuration = 3;

// show the next and previous image previews?
var showImagePreview = true;

// don't want the lightbox?
var useLightbox = true;

// don't like the PhotoRank mouseover?
var displaySmugPopular = true;

// new gallery styles can change how many thumbs to display (per page is beta)
var zoomGalleryPhoto = false;
var showPhotoBar = true;
var fadeOutTime = 0;
var fadeInTime = 0;
var photoBarDelay = 0;

// force a smugmug size; options: Resizeable, Large, Small
var SmugMugSize = "Small";

SM.SmugMug = {
    'config': {
        'size': 'auto'
    }
};

SM.PhotoBar = {
    'config': {
        'position': 'right'
    }
};

// aliases for YUI stuff
var YD = YAHOO.util.Dom;
var YE = YAHOO.util.Event;
var YA = YAHOO.util.Anim;
var Yua = YAHOO.env.ua;

// we need to do things on the page load
//YE.addListener(window, 'load', function(e) {
YE.onDOMReady(function() {
    pageLoaded = true;

    getTZ();

    clearCheckboxes();

    changeInputs();

    //createCookie('previewThemeID', '', -365);
    //createCookie('previewThemeCat', '', -365);

    SM.util.setCookie('previewThemeID', '', -365);
    SM.util.setCookie('previewThemeCat', '', -365);
});

var pageLoaded = false;

var windowLoaded = false;
YE.on(window,'load',function() {
    windowLoaded = true;
});


// timezone stuff for local dates
function getTZ() {
    var rightNow = new Date();
    var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
    var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
    var temp = date1.toGMTString();
    var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));

    temp = date2.toGMTString();
    var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
    var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);

    var timeZone = hoursDiffStdTime + ((hoursDiffDaylightTime === hoursDiffStdTime) ? ',false' : ',true');

    /*
    if (readCookie('tZone') != timeZone) {
        createCookie("tZone", timeZone, 365);
    }
    */

    if (SM.util.getCookie('tZone') !== timeZone) {
        SM.util.setCookie('tZone', timeZone, 365);
    }
}


function removeFromDOM(el) {
    if (typeof el === "string") {
        el = YD.get(el);
    }

    if (!el) {
        return;
    }

    YE.purgeElement(el, true);

    while (el.hasChildNodes()) {
        el.removeChild(el.childNodes[0]);
    }

    el.parentNode.removeChild(el);
}


/**
 * DEPRECATED - use YE.addListener instead
 */
function addEvent(el, sType, fn) {
    YE.addListener(el, sType, fn);
}

/**
 * DEPRECATED - Use SM.util.setCookie
 */
function setCookie(name, value, expires, path, domain, secure) {
    var navigation = name + "=" + encodeURIComponent(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = navigation;
}

/**
 * DEPRECATED - Use SM.util.setCookie
 */
var createCookie = SM.util.setCookie;


/**
 * DEPRECATED - Use SM.util.getCookie
 */
var readCookie = SM.util.getCookie;


//prevents Buttons from being hit twice
function disableButton() {
    document.loginForm.submitButton.disabled=true;
    return true;
}

// Window transitions
function windowOpener(url, name, args) {
    if (typeof(window.popupWin) !== "object") {
        window.popupWin = window.open(url,name,args);
    } else {
        if (!window.popupWin.closed) {
            window.popupWin.close();
            window.popupWin = window.open(url,name,args);
            // popupWin.location.href = url;
        } else {
            window.popupWin = window.open(url,name,args);
            // window.popupWin.focus();
        }
    }
}

function closeWindow() {
    if (!opener.closed) {
        opener.focus();
        self.close();
    }

    self.close();
}


/**
 * var remote; function uploadStatus(); and function uploadStatusKill
 * should really go in the uploader page instead of in the global JS
 */
var remote;

function uploadStatus() {
    remote = window.open("","uploadstatus","width=450,height=400,location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
    remote.location.href = "/photos/uploadstatus.mg";

    if (remote.opener === null) {
        remote.opener = window;
    }

    remote.opener.name = "opener";
}

function uploadStatusKill() {
    remote = window.open("","uploadstatus","width=350,height=400,location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes");
    remote.close();
}


/**
 * This is so bad.  Please don't use this.
 */
function handleJS(response) {
    eval(response);
}


/**
 * DEPRECATED - ajax_encode_array, ajax_query
 * Don't use this function, write your own using
 * YUI connection manager.  This is so we don't
 * break anything currently using ajax_query().
 */
function ajax_query(callback, url, postArray, asText) {
    var postData = [], xhr;

    for (var p in postArray) {
        postData.push(encodeURIComponent(p) + '=' + encodeURIComponent(postArray[p]));
    }

    var success = function(o) {
        if (typeof callback === 'function') {
            callback(asText ? o.responseText : o.responseXML);
        }
    };

    var failure = function() {
        };

    var xhrCallback = {
        'success': success,
        'failure': failure
    };

    if (postData.length === 0) {
        xhr = YAHOO.util.Connect.asyncRequest('GET', url, xhrCallback);
    } else {
        xhr = YAHOO.util.Connect.asyncRequest('POST', url, xhrCallback, postData.join('&'));
    }

}


// check input boxes for values and sub if needed
function checkInput(checkFor, checkHere, useThis) {
  // Use Sizzle instead of YUI to perform this check
  // on multiple elements when they are incorrectly
  // added to a page. (i.e. more than one element
  // with the same id)
  if (typeof(Sizzle) != 'undefined') {
    var matches = Sizzle('*[id=' + checkHere + ']');
    for (var i = 0; i < matches.length; i++) {
      if (matches[i] && matches[i].value == checkFor) {
        matches[i].value = useThis;
      }
    }
  } else {
    checkHere = YD.get(checkHere);
    if (checkHere && checkHere.value === checkFor) {
      checkHere.value = useThis;
    }
  }
}


// send someone away
function goHere(url) {
    if (url !== '') {
        location.href = url;
    }
}


function toggleDIV(on, off, style) {
    var i, styles, ons, offs;

    if (style !== ''  && on !== '') {
        styles = style.split(",");
        ons = on.split(",");

        for (i = 0; i < ons.length; i++) {
            YD.setStyle(ons[i], 'display', styles[i]);
        }
    }

    if (off !== '') {
        offs = off.split(",");

        for (i = 0; i < offs.length; i++) {
            YD.setStyle(offs[i], 'display', 'none');
        }
    }
}


function URLEncode(plaintext) {
    var sendText = '';

    for (var i = 0; i < plaintext.length; i++) {
        if (plaintext.charCodeAt(i) > 255) {
            sendText += "&#" + Number(plaintext.charCodeAt(i)).toString() + ";";
        } else {
            if (plaintext.charCodeAt(i) === "10") {
                sendText += plaintext.charAt(i);
            } else if (plaintext.charCodeAt(i) === "8220") {
                sendText += "\"";
            } else if (plaintext.charCodeAt(i) === "8221") {
                sendText += "\"";
            } else if (plaintext.charCodeAt(i) === "8217") {
                sendText += "'";
            } else if (plaintext.charCodeAt(i) === "8220") {
                sendText += "\"";
            } else {
                sendText += plaintext.charAt(i);
            }
        }
    }

    return encodeURIComponent(sendText.replace(new RegExp(/\+/g),"&#43;"));
}


function URLDecode(encoded) {
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var plaintext = "";
    var i = 0, ch;

    while (i < encoded.length) {
        ch = encoded.charAt(i);

        if (ch === "+") {
            plaintext += " ";
            i++;
        } else if (ch === "%") {
            if (i < (encoded.length-2) && HEXCHARS.indexOf(encoded.charAt(i+1)) !== -1 && HEXCHARS.indexOf(encoded.charAt(i+2)) !== -1 ) {
                plaintext += unescape( encoded.substr(i,3) );
                i += 3;
            } else {
                alert( 'Bad escape combination near ...' + encoded.substr(i) );
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
             plaintext += ch;
             i++;
        }
    } // while

    return plaintext;
}


function setOpt(theSel, optValue) {
    var opt = theSel.options;

    for (var i = 0, len = opt.length; i < len; i++) {
        if (opt[i].value === optValue) {
            theSel.selectedIndex = i;
            return true;
        }
    }

    return false;
}


// refreshing in moz still leaves checkmarked boxes, clear them for these things: (arrange tool, hide photo tool)
function clearCheckboxes() {
    var i, inputTags = document.getElementsByTagName("input");

    for (i = 0; i < inputTags.length; i++) {
        if (inputTags[i].type === "checkbox" && inputTags[i].className === "refreshClear") {
            inputTags[i].checked = false;
        }
        if (inputTags[i].type === "checkbox" && inputTags[i].className === "refreshCheck") {
            inputTags[i].checked = true;
        }
        if (inputTags[i].type === "radio" && YD.hasClass(inputTags[i],"refreshCheck")) {
            inputTags[i].checked = true;
        }
    }
}


var disabledPreview = false;

function previewImage(e, imgSrc) {
    if (showImagePreview && pageLoaded && !disabledPreview) {
        // remove any previous preview first
        var el = YD.get('floatingPreview');

        if (el) {
            el.parentNode.removeChild(el);
        }

        if (!e) {
            e = window.event;
        }

        var posx = 0;
        var posy = 0;

        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        } else if (e.clientX || e.clientY) {
            posx = e.clientX + document.documentElement.scrollLeft;
            posy = e.clientY + document.documentElement.scrollTop;
        }

        var body = document.getElementsByTagName("body")[0];
        var floatingPreview = document.createElement("img");
        floatingPreview.setAttribute("id", "floatingPreview");

        if (!Yua.webkit) {
            floatingPreview.style.visibility = "hidden";

            YE.addListener(floatingPreview, 'load', function(e) {
                var previewPop = setTimeout(function() {
                    YD.setStyle(floatingPreview,'visibility','visible');
                    previewOnload(posx,posy);
                }, 1000);
            });
        } else {
            floatingPreview.onload = function() {
              previewOnload(posx, posy);
            };
        }

        floatingPreview.style.top = (posy+2)+"px";
        floatingPreview.style.left = (posx+2)+"px";

        body.appendChild(floatingPreview);
        floatingPreview.setAttribute("src", imgSrc);
    }
}

function previewOnload(posx, posy) {
    var toTop, toLeft;

    // do we need to adjust the location?
    if (document.documentElement.scrollTop) {
        toTop = document.documentElement.scrollTop;
        toLeft = document.documentElement.scrollLeft;
    } else {
        toTop = document.body.scrollTop;
        toLeft = document.body.scrollLeft;
    }

    var el = YD.get('floatingPreview');

    if (el) {
        if (el.offsetHeight + posy + 2 > toTop + screenHeight()) {
            YD.setStyle(el, 'top', posy - el.offsetHeight - 2 + 'px');
        }

        if (el.offsetWidth + posx + 2 > toLeft + screenWidth()) {
            YD.setStyle(el, 'left', posx - el.offsetWidth - 2 + 'px');
        }
    }
}

function removePreview() {
    var el = YD.get('floatingPreview');

    if (el) {
        el.parentNode.removeChild(el);
    }
}


/**
 * DEPRECATED - Use YD.getX
 */
var findposX = YD.getX;


/**
 * DEPRECATED - Use YD.getY
 */
var findposY = YD.getY;


/**
 * DEPRECATED - Use YD.getStyle
 */
var getCSSProp = YD.getStyle;


/**
 * new helpie hotness...not quite ready for primetime
 */
/*
SM.helpie = new YAHOO.widget.Tooltip('sm-helpie');
SM.helpie.doHide = function() {
    return true;
}
*/

function createHelpie(e, title, bodyText, width) {
    if (!e) {
        e = window.event;
    }

    var target = e.currentTarget || e.srcElement;

/*
    SM.helpie.cfg.setProperty('context', target);
    SM.helpie.cfg.setProperty('text', '<h3 class="notopmargin title">' + URLDecode(title) + '</h3>' + URLDecode(bodyText));
    SM.helpie.cfg.setProperty('width', width + 'px');
    SM.helpie.onContextMouseOver.call(target, e, SM.helpie);
*/

    var posx = YD.getX(target);
    var posy = YD.getY(target) + target.offsetHeight + 10;

    var body = document.body;

    if (Yua.ie === 6) {
        var helpieFrame = document.createElement("iframe");
        helpieFrame.id = 'helpieFrame';
        helpieFrame.src = 'javascript:false';
        helpieFrame.style.top = (posy) + "px";
        helpieFrame.style.left = (posx) + "px";

        body.appendChild(helpieFrame);
    }

    var helpie = document.createElement("div");
    helpie.setAttribute("id", "helper");

    if (width != '') {
        helpie.style.width = width+"px";
    }

    helpie.style.top = (posy) + "px";
    helpie.style.left = (posx) + "px";

    if (title != "") {
        title = '<h3 class="notopmargin title">' + URLDecode(title) + '</h3>';
    }

    helpie.innerHTML = title + URLDecode(bodyText);

    body.appendChild(helpie);

    if (Yua.ie === 6 && helpieFrame) {
        helpieFrame.style.height = helpie.offsetHeight;
        helpieFrame.style.width = helpie.offsetWidth;
    }

    if (document.documentElement.scrollTop) {
        var toTop = document.documentElement.scrollTop;
        var toLeft = document.documentElement.scrollLeft;
    } else {
        var toTop = document.body.scrollTop;
        var toLeft = document.body.scrollLeft;
    }

    if (helpie.offsetHeight + posy + 2 > toTop + screenHeight()) {
        helpie.style.top = (toTop + screenHeight()) - helpie.offsetHeight + "px";

        if (Yua.ie === 6 && helpieFrame) {
            helpieFrame.style.top = (toTop + screenHeight()) - helpie.offsetHeight + "px";
        }
    }

    if (helpie.offsetWidth + posx + 2 > toLeft + screenWidth()) {
        helpie.style.left = (toLeft + screenWidth()) - helpie.offsetWidth + "px";
        if (Yua.ie === 6 && helpieFrame) {
            helpieFrame.style.left = (toLeft + screenWidth()) - helpie.offsetWidth + "px";
        }
    }
}

function removeHelpie() {
    var helpie = YD.get('helper');
    var helpieFrame = YD.get('helpieFrame');

    if (helpie) {
        helpie.parentNode.removeChild(helpie);
    }

    if (helpieFrame) {
        helpieFrame.parentNode.removeChild(helpieFrame);
    }
}


/**
 * DEPRECATED - Use YD.getViewportWidth
 */
var screenWidth = YD.getViewportWidth;


/**
 * DEPRECATED - Use YD.getViewportHeight
 */
var screenHeight = YD.getViewportHeight;


function randomString(string_length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';

    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }

    return randomstring;
}


/**
 * only called from galleries_ajax.js
 */
function scrollAreas(status) {
    if (status === "add") {
        var body = document.body;
        var scrollTop = document.createElement("div");
        scrollTop.id = 'scrollTop';

        scrollTop.onmouseover = function() {
            goScroll(-1);
        };

        scrollTop.onmouseout = function() {
            goScroll(0);
        };

        body.appendChild(scrollTop);

        var scrollBottom = document.createElement("div");
        scrollBottom.id = 'scrollBottom';

        scrollBottom.onmouseover = function() {
            goScroll(1);
        };

        scrollBottom.onmouseout = function() {
            goScroll(0);
        };

        body.appendChild(scrollBottom);
    } else {
        var scrollTop = YD.get('scrollTop');

        if (scrollTop) {
            scrollTop.parentNode.removeChild(scrollTop);
        }

        var scrollBottom = YD.get('scrollBottom');

        if (scrollBottom) {
            scrollBottom.parentNode.removeChild(scrollBottom);
        }
    }
}


/**
 * Begin input highlight stuffs
 * cool subtle FX that change BG color of input you are focues on:
 * ppft, sez you.  focues?  -LS
 */
var highlightInputs = false;

function changeInputs() {
    var inputTags;

    if (highlightInputs) {
        inputTags = YD.getElementsBy(function(el) {
            if (el.type === 'text' || el.type === 'password') {
                return true;
            } else {
                return false;
            }
        }, 'input', null, function(el) {
            el.onfocus = function() {
                highlightInput(this.id);
            };

            el.onblur = function() {
                unhighlightInput(this.id);
            };

        });
    }
}


function highlightInput(choice) {
    setTimeout('changeBGColor("' + choice + '","#f7fbf0")', 50);
    setTimeout('changeBGColor("' + choice + '","#eff8e0")', 100);
    setTimeout('changeBGColor("' + choice + '","#e7f4d0")', 150);
    setTimeout('changeBGColor("' + choice + '","#dff0c0")', 200);
    setTimeout('changeBGColor("' + choice + '","#d7edb1")', 250);
    setTimeout('changeBGColor("' + choice + '","#cfe9a1")', 300);
    setTimeout('changeBGColor("' + choice + '","#c7e591")', 350);
    setTimeout('changeBGColor("' + choice + '","#bfe181")', 400);
    setTimeout('changeBGColor("' + choice + '","#b7de72")', 450);
    setTimeout('changeBGColor("' + choice + '","#afda62")', 500);
}


function unhighlightInput(choice) {
    setTimeout('changeBGColor("' + choice + '","#ffffff")', 500);
    setTimeout('changeBGColor("' + choice + '","#f7fbf0")', 450);
    setTimeout('changeBGColor("' + choice + '","#eff8e0")', 400);
    setTimeout('changeBGColor("' + choice + '","#e7f4d0")', 350);
    setTimeout('changeBGColor("' + choice + '","#dff0c0")', 300);
    setTimeout('changeBGColor("' + choice + '","#d7edb1")', 250);
    setTimeout('changeBGColor("' + choice + '","#cfe9a1")', 200);
    setTimeout('changeBGColor("' + choice + '","#c7e591")', 150);
    setTimeout('changeBGColor("' + choice + '","#bfe181")', 100);
    setTimeout('changeBGColor("' + choice + '","#b7de72")', 50);
}


function changeBGColor(choice, color) {
    YD.setStyle(choice, 'backgroundColor', color);
}
/**
 * end input highlight stuffs
 */


function toggleShow(choice, link, openClass, closeClass) {
    if(!YD.get(choice).offsetWidth) {
        if (link) {
            YD.replaceClass(link, openClass, closeClass);
        }

        YD.setStyle(choice, 'display', 'block');

        if (document.documentElement.scrollTop) {
            var toTop = document.documentElement.scrollTop;
        } else {
            var toTop = document.body.scrollTop;
        }

        choice = YD.get(choice);

        if (choice.offsetHeight + findposY(choice) > toTop + screenHeight()) {
            var scrollY = choice.offsetHeight + findposY(choice) - screenHeight();

            window.scrollTo(0, scrollY);
        }
    } else {
        if (link) {
            YD.replaceClass(link, closeClass, openClass);
        }

        YD.setStyle(choice, 'display', 'none');
    }
}


/**
 * Returns the highest z-index on the page
 */
function getZindex(obj) {
    var zIndex = 0, zCheck, allObjs;

    if (obj.offsetParent) {
        while(1) {
            zCheck = parseInt(YD.getStyle(obj, 'zIndex'), 10);

            if (!isNaN(zCheck) && zCheck > zIndex) {
                zIndex = zCheck;
            }

            if (!obj.offsetParent) {
                break;
            }

            obj = obj.offsetParent;
        }
    } else {
        allObjs = document.getElementsByTagName("*");

        for (var i = 0, len = allObjs.length; i < len; i++) {
            zCheck = parseInt(YD.getStyle(allObjs[i], 'zIndex'), 10);

            if (!isNaN(zCheck) && zCheck > zIndex) {
                zIndex = zCheck;
            }
        }
    }

    return parseInt(zIndex, 10) + 1;
}



/**
 * DEPRECATED - Use SM.util.getCloneDimensions
 */
var getCloneDimensions = SM.util.getCloneDimensions;


/**
 * Displays the little page working message in the top left corner
 */
var pageWorkingOn = false;


function pageWorking(message, icon) {
    if (!YD.inDocument('pageWorking')) {
        var body = document.body;
        var pageWorking = document.createElement("div");
        var pageWorkingContent = document.createElement("div");

        pageWorking.id = 'pageWorking';
        pageWorkingContent.id = 'pageWorkingContent';
        body.appendChild(pageWorking);

        pageWorking.appendChild(pageWorkingContent);
        YD.setStyle(pageWorking, 'zIndex', getZindex(body));
        pageWorkingContent.innerHTML = message;

        var workingAnim = new YA('pageWorking');
        workingAnim.attributes.height = { to: 43 };
        workingAnim.duration = .5;
        workingAnim.method = YAHOO.util.Easing.backOut;
        workingAnim.onComplete.subscribe(function(e) {
            YD.setStyle('pageWorkingContent', 'visibility', 'visible');
            setTimeout("eval('pageWorkingOn = true')", 1000);
        });

        workingAnim.animate();
    } else {
        YD.get('pageWorkingContent').innerHTML = message;
    }
}


function removePageWorking() {
    if (YD.get('pageWorking')) {
        if (pageWorkingOn) {
            YD.setStyle('pageWorkingContent', 'visibility', 'hidden');

            var workingAnim = new YA('pageWorking');
            workingAnim.attributes.height = { to: 0 };
            workingAnim.duration = .75;
            workingAnim.method = YAHOO.util.Easing.backIn;

            workingAnim.onComplete.subscribe(function(e) {
                var el = YD.get('pageWorking');
                el.parentNode.removeChild(el);
            });

            workingAnim.animate();

            pageWorkingOn = false;
        } else {
            setTimeout("removePageWorking()", 500);
        }
    }
}
/**
 * End pageworking stuffs
 */


/**
 * Toggle the height of elements
 */
function toggleHeight(id) {
    var obj = YD.get(id);

    if (parseInt(YD.getStyle(obj,'height')) === 0) {
        YD.setStyle(obj,'display','block');
        var objHeight = getCloneDimensions(id).height;
        var myAnim = new YA(id);

        myAnim.attributes.height = { to: objHeight };
        myAnim.duration = .25;
        myAnim.animate();

        // will the object be seen off the screen?
        if (document.documentElement && document.documentElement.scrollTop) {
            var toTop = document.documentElement.scrollTop;
        } else if (document.body) {
            var toTop = document.body.scrollTop;
        }

        if (YD.getY(obj) + objHeight > toTop + YD.getViewportHeight()) {
            if (!Yua.webkit) {
                var element = document.documentElement;
            } else {
                var element = document.body;
            }

            var scrollAnim = new YAHOO.util.Scroll(element, {
                scroll: { by: [0, (YD.getY(obj) + objHeight) - (toTop + YD.getViewportHeight())] }
            },.25);

            scrollAnim.animate();
        }
    } else {
        var myAnim = new YA(id);
        myAnim.attributes.height = { to: 0 };
        myAnim.duration = .25;
        myAnim.onComplete.subscribe(function(e) {
            YD.setStyle(obj,'display','none');
        });

        myAnim.animate();
    }
}

function changeRedirectForAjax(anchor) {
    if (getHash()) {
        anchor.href = anchor.href+"&hash="+getHash();
    }
}


function getHash() {
    if (!window.location.href.split("#")[1]) {
        return false;
    }

    return window.location.href.split("#")[1];
}


/**
 * DEPRECATED - Use SM.util.normalizeURL(url)
 */
var convertAjaxURL = SM.util.normalizeURL;


/**
 * DEPRECATED - Use SM.util.trimString(str)
 */
var TrimString = SM.util.trimString;


var onPhotoShow = new YAHOO.util.CustomEvent('photoShown', window, false, YAHOO.util.CustomEvent.FLAT);


function loadedImageRPC(givenID, givenSize, givenKey) {
    var Size;

    if (!givenKey) {
        givenKey = photoInfo[givenID] ? photoInfo[givenID].ImageKey : '';
    }

    switch (givenSize) {
        case "Small":
            Size = "S";
            break;
        case "Medium":
            Size = "M";
            break;
        case "Large":
            Size = "L";
            break;
        case "XLarge":
            Size = "XL";
            break;
        case "X2Large":
            Size = "X2";
            break;
        case "X3Large":
            Size = "X3";
            break;
        case "Original":
            Size = "O";
            break;
        default: Size = givenSize;
    }

    if (Size) {
        var postArray = [];
        postArray.tool = 'checkSecurity';
        postArray.ImageID = givenID;
        postArray.ImageKey = givenKey;
        postArray.S = Size;
        ajax_query('', '/rpc/gallery.mg', postArray, true);

        onPhotoShow.fire({ ImageID : givenID, Size : Size });
    }
}


/**
 * Re-fires user analytics trackers when the
 * main photo dynamically changes.
 * Listens for onPhotoShow event, which only
 * gets fired from smugmug style gallery right
 * now.
 *
 * Can move to gallery_ajax or galleries_ajax
 * Or can go into a footer script so long as
 * it comes after cobrand footer
 */
(function() {
    var trackerLoadCount;

    onPhotoShow.subscribe(function(o) {
        if (!trackerLoadCount) {
            trackerLoadCount = 1;
            return;
        }

        // Statcounter
        var s = document.getElementsByTagName('script');
        var re = /statcounter\.com\/.+counter(_xhtml)?\.js$/;

        for (var i = 0; i < s.length; i++) {
            if (re.test(s[i].src)) {
                sc_invisible = 1;

                var newEl = document.createElement('script');
                newEl.src = s[i].src;

                s[i].parentNode.replaceChild(newEl, s[i]);

                break;
            }
        }

        // QuantCast
        if (typeof quantserve === 'function') {
            _qpixelsent = '';
            quantserve();
        }

        //var reportURL = location.pathname;
        var reportURL = SM.util.normalizeURL();

        // Google Analytics - urchin tracker
        if (typeof urchinTracker === 'function') {
            urchinTracker(reportURL);
        }

        // Google Analytics v3
        if (typeof pageTracker === 'object') {
            pageTracker._trackPageview(reportURL);
        }

        // Site Meter
        if (typeof SiteMeter === 'object') {
            var sImage = "http://" + SiteMeter.ServerName + "/meter.asp?site=" + SiteMeter.CodeName;
            sImage += "&refer=" + SiteMeter.getReferral().replace(/(gallery\/\w+)\S*#/, '$1/1/');

            if (SiteMeter.IP !== '') {
                sImage += "&ip=" + SiteMeter.IP;
            }

            sImage += "&w=" + window.screen.width;
            sImage += "&h=" + window.screen.height;
            sImage += "&clr=" + window.screen.colorDepth;
            sImage += "&lang=" + escape(navigator.language ? navigator.language : navigator.userLanguage);

            if (SiteMeter.SecurityCode !== '') {
                sImage += "&sc=" + escape(SiteMeter.SecurityCode);
            }

            sImage += "&pg=" + escape(document.location.toString().replace(/(gallery\/\w+)\S*#/, '$1/1/'));
            sImage += "&js=1&rnd=" + Math.random();

            if (SiteMeter.trackingImage) {
                SiteMeter.trackingImage.src = sImage;
            }
        }

        trackerLoadCount++;

        });
})();


/**
 * The little spinning busy icon in the top left
 */
function ajaxThrobber(state) {
    var throbber = YD.get('throbber');

    if (!throbber) {
        return;
    }

    if (state === 'on') {
        YD.setStyle(throbber, 'zIndex', getZindex(document.body));
        YD.setStyle(throbber, 'visibility', 'visible');
    }

    if (state === 'off') {
        YD.setStyle(throbber, 'visibility', 'hidden');
    }
}


/**
 * converts sizes...i guess
 */
function findSize(passed) {
    var map = {
        's': 'Small',
        'm': 'Medium',
        'l': 'Large',
        'xl': 'XLarge',
        'x2': 'X2Large',
        'x3': 'X3Large',
        'o': 'Original',
        'a': 'Auto',
        'small': 'S',
        'medium': 'M',
        'large': 'L',
        'xlarge': 'XL',
        'x2large': 'X2',
        'x3large': 'X3',
        'original': 'O',
        'auto': 'A'
    };

    var size = map[passed.toLowerCase()];

    if (!size) {
        size = passed.length > 2 ? 'M' : 'Medium';
    }

    return size;
}


function addslashes(str) {
    str = str.replace(/\'/g,'\\\'');
    str = str.replace(/\"/g,'\\"');
    str = str.replace(/\\/g,'\\\\');
    str = str.replace(/\0/g,'\\0');

    return str;
}


function stripslashes(str) {
    str = str.replace(/\\'/g,'\'');
    str = str.replace(/\\"/g,'"');
    str = str.replace(/\\\\/g,'\\');
    str = str.replace(/\\0/g,'\0');

    return str;
}


/**
 * SmugMug Google Analytics tracker
 * Will use any existing version of GA
 * If no existing version of GA is found
 * GA v3 will be used
 *
 * Can go in a footer script, so long as it
 * is below the cobrand footer.
 */
(function() {
    var smug_uacct = location.host.indexOf('smugmug.net') > -1 ? 'UA-138402-7' : 'UA-138402-3';

    var GA_Urchin = function() {
        //var reportURL = location.pathname;
        var reportURL = SM.util.normalizeURL();

        // someone is trying to track already
        try {
            if (_uacct) {
                var hold_uacct = _uacct;
            }
        } catch (err) {
            var hold_uacct = null;
        }

        _uacct = smug_uacct;

        urchinTracker(reportURL);

        if (hold_uacct) {
            _uacct = hold_uacct;
        } else {
            _uacct = null;
        }
    };

    var GA_Version3 = function() {
        //var reportURL = location.pathname;
        var reportURL = SM.util.normalizeURL();

        if (typeof smugTracker === 'object') {
            smugTracker._trackPageview(reportURL);
        }
    };

    var trackGA = function() {
        var createSmugTracker = function(uacct) {
            smugTracker = _gat._getTracker(uacct);
            //smugTracker._setDomainName('.smugmug.com');
            smugTracker._initData();
        };

        if (typeof urchinTracker === 'function') {
            GA_Urchin();
        } else {
            if (typeof _gat === 'object') {
                if (typeof smugTracker !== 'object') {
                    createSmugTracker(smug_uacct);
                }

                GA_Version3();
            } else {
                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.src = (('https:' === document.location.protocol) ? 'https://ssl.' : 'http://www.') + 'google-analytics.com/ga.js';

                document.getElementsByTagName("head")[0].appendChild(s);

                var trackerLoaded = setInterval(function () {
                    if (typeof _gat === "object") {
                        clearInterval(trackerLoaded);
                        createSmugTracker(smug_uacct);
                        GA_Version3();
                    }
                }, 50);
            }
        }

        };

    YE.onDOMReady(function() {
        if (YD.hasClass(document.body,'smugmug_ajax')) {
            onPhotoShow.subscribe(trackGA);
        } else {
            YE.on(window,'load',trackGA);
        }
    });
})();


/**
 * DEPRECATED - use SM.util.copy2clipboard
 */
var copy2CB = SM.util.copy2clipboard;


function insertAfter(newElement,targetElement) {
  //target is what you want it to go after. Look for this elements parent.
  var parent = targetElement.parentNode;

  //if the parents lastchild is the targetElement...
  if(parent.lastchild === targetElement) {
    //add the newElement after the target element.
    parent.appendChild(newElement);
    } else {
    // else the target has siblings, insert the new element between the target and it's next sibling.
    parent.insertBefore(newElement, targetElement.nextSibling);
    }
}


/**
 * Namespace the flash stuff here for the time being
 * since people are putting slideshows on their homepage.
 * We can move it later.
 */
SM.namespace('flash');

SM.flash.insertSlideshow = function(w, h, params) {
    var args = "noTagBacks=true&amp;";

    for (var i in params) {
        args += i + "=" + params[i] + "&amp;";
    }

    document.writeln('<object width="100%" height="100%" align="middle">'+
                '<param name="movie" value="/ria/ShizamSlides-'+SM.appVersion['ShizamSlides']+'.swf?' + args + '" />'+
                '<param name="wmode" value="transparent" />'+
                '<embed src="/ria/ShizamSlides-'+SM.appVersion['ShizamSlides']+'.swf?'+ args + '" wmode="transparent" width="' + w + '" height="\
                ' + h + '" type="application/x-shockwave-flash" allowScriptAccess="always" allowNetworking="all"/><\/object>');

    return 1;
};

SM.flash.insertSlideshowIntoElement = function(elementID, w, h, params) {
    var args = "noTagBacks=true&amp;";
    var objectHTML = '';

    for (var i in params) {
        args += i + "=" + params[i] + "&amp;";
    }
    
    objectHTML = '<div style="width: ' + w + '; height: ' + h + ';"><object width="' + w + '" height="' + h + '" align="middle"><param name="movie" value="/ria/ShizamSlides-' + SM.appVersion['ShizamSlides'] + '.swf?' + args + '" /><param name="wmode" value="transparent" /><embed src="/ria/ShizamSlides-' + SM.appVersion['ShizamSlides'] + '.swf?' + args + '" wmode="transparent" width="' + w + '" height="' + h + '" type="application/x-shockwave-flash" allowScriptAccess="always" allowNetworking="all"/><\/object></div>';

    YD.get(elementID).innerHTML = objectHTML;

    return 1;
};

SM.flash.insertFlashIntoElement = function(elementID, w, h, src, params) {
    var args = "noTagBacks=true&amp;";

    for (var i in params) {
        args += i + "=" + params[i] + "&amp;";
    }

    YD.get(elementID).innerHTML = '<div style="width: ' + w + '; height: ' + h + ';"><object width="100%" height="100%" align="middle"><param name="movie" value="' + src + '?' + args + '" /><param name="wmode" value="transparent" /><param name="allowFullScreen" value="true" /><embed src="' + src + '?'+ args + '" wmode="transparent" allowFullScreen="true" width="' + w + '" height="' + h + '" type="application/x-shockwave-flash" allowScriptAccess="always" allowNetworking="all"/><\/object></div>';

    return 1;
};


SM.FB = function() {
   return {
      init: function(fncSuc, fncFail) {
        YAHOO.util.Get.script('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php', {
            timeout:10,
            onSuccess: function() {
                FB.init(SM.APIKey['fbConnect'], "/services/fbconnect/xd_receiver.htm");
                if(typeof fncSuc=='function') fncSuc();
            },
            onFailure: function() {
                if(typeof fncFail=='function') fncFail();
            },
            onTimeout: function() {
                if(typeof fncFail=='function') fncFail();
            }
        });
    },
    
      login: function(fncSuc) {
            FB.Connect.requireSession(function() { 
                if(typeof fncSuc=='function') fncSuc();
            });
      },
      
      logout: function(fncSuc) {
            FB.Connect.logout(function() {
                if(typeof fncSuc=='function') fncSuc();
            });
      }
   };
}();



/**
 * createSWF was the dumb name used for the javascript
 * function that created the shizam slideshow.  Keep
 * the original definition but point it to a more
 * appropriately named function.
 *
 * DEPRECATED - use SM.flash.insertSlideshow
 */
var createSWF = SM.flash.insertSlideshow;


/**
 * Gotta fix the ridiculous default behavior of the
 * YUI menu button to always close the menu when its clicked.
 *
 */
try {
    YAHOO.widget.Button.prototype._onMenuClick = function(p_sType, p_aArgs) {
        var oItem = p_aArgs[1],
            oSrcElement;

        if (oItem) {
            if (YD.hasClass(oItem.element,'yuimenuitem-hassubmenu')) {
              YE.preventDefault(p_aArgs);
              YE.stopPropagation(p_aArgs);
              YE.stopEvent(p_aArgs);
              }
        
            this.set("selectedMenuItem", oItem);

            oSrcElement = this.get("srcelement");

            if (oSrcElement && oSrcElement.type == "submit") {
                this.submitForm();
            }
            
            
        }
    };
} catch (e) {
    // likely dont have button.  s'okay.
}