/*
    http://www.JSON.org/json2.js
    2009-08-17

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

"use strict";

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
function getXMLObject() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP")) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
    };
    return xmlhttp;
}
;

function syncRequest(url, parameters) {
     var xmlhttp = getXMLObject();
    // to be ensure non-cached version of response
    url = url + "?rnd=" + Math.random();

    xmlhttp.open("POST", url, false); //false means synchronous
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(parameters);

    var responseText = xmlhttp.responseText;
    return responseText;
    
}
;

function asyncRequest(url, parameters, successFunction, failureFunction) {
    http_request = getXMLObject();
    url = url + "?rnd=" + Math.random();
    http_request.onreadystatechange = function() {
        if (http_request.readyState == 4) {

            if (http_request.status == 200) {
                if (successFunction) { successFunction(http_request.responseText); };
            } else {
            alert(http_request.responseText);
                if (failureFunction) { failureFunction(); };
            }
            ;
        }
        ;
    }
	;
    http_request.open('POST', url, true); /* true = async */
    http_request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    http_request.send(parameters);
};
var _timeoutID = -1;
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);

function FireDefaultButton(event, target) {
    if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
        var defaultButton;
        if (__nonMSDOMBrowser) {
            defaultButton = document.getElementById(target);
        }
        else {
            defaultButton = document.all[target];
        };
        if (defaultButton && typeof (defaultButton.click) != "undefined") {
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            return false;
        };
    };
    return true;
}
;

function imageAD(cycle, pos, loop) {
    window.clearTimeout(_timeoutID);
    var Ad = document.getElementById("ctl00_imgNavAD");
    if (Ad) {
        if (cycle < 3) {
            pos = parseInt(pos) - 215;
            cycle++;
        } else {
            cycle = 1;
            loop++;
            pos = -219;
        };
        Ad.style.backgroundPosition = pos + "px -123px";
        if (loop < 3) { _timeoutID = setTimeout(function() { imageAD(cycle, pos, loop); }, 1500); };
    };
}
;

function addDropDownOption(value, text, ddl) {
    var optn = document.createElement("option");
    optn.text = text;
    optn.value = value;
    ddl.options.add(optn);

    return optn;
}
;

function setDropdownByValue(ddl, value) {
    for (var o = 0; o < ddl.options.length; o++) {
        if (value == ddl.options[o].value) {
            ddl.options[o].selected = true;
            return o;
        }
        ;
    }
    ;
    return -1;
}
;

function replace(fullstr, oldstr, newstr) {
    var index = fullstr.indexOf(oldstr);
    var teststr = fullstr;
    var leftSide = rightSide = "";
    while (index > -1) {
        leftSide = teststr.substr(0, index);
        rightSide = teststr.substr(index + oldstr.length);

        teststr = leftSide + newstr + rightSide;

        index = teststr.indexOf(oldstr);
    }
    ;

    return teststr;
}
;

function queryString(key) {
    var value = "";
    var loc = window.location.toString().toLowerCase();
    if (loc.indexOf("?") > -1) {
        if (loc.indexOf(key + "=") > -1) {
            value = loc.substr(loc.indexOf(key + "=") + key.length + 1);
            if (value.indexOf("&") > -1) {
                value = value.substr(0, value.indexOf("&"));
            }
            ;
        }
        ;
    }

    return value;
}
;

function WindowSize() {
    var WinSize = new Object();
    WinSize.Width = 0;
    WinSize.Height = 0;

    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    };

    WinSize.Width = myWidth;
    WinSize.Height = myHeight;

    return WinSize;
};

function getPos(off) {
    if (off.offsetParent) {
        curleft = off.offsetLeft;
        curtop = off.offsetTop;
        while (off) {
            curleft += off.offsetLeft;
            curtop += off.offsetTop;
            off = off.offsetParent;
        }
    }
    ;
    return { "left": curleft, "top": curtop };
};

//_timeoutID = setTimeout(function() { imageAD(1, -219, 1); }, 1500);

function openWindow(uri, args, name) {
    var newWin = window.open(uri, name, args);
};

function getWindowLocation() {
    var Location = window.location.toString();
    var index = Location.indexOf("?");
    if (index > -1) {
        return Location.substr(0, index);
    }

    return Location;
};

var _feedbackTimer = null;
function ClearFeedback() {
    if (_feedbackTimer) { window.clearTimeout(_feedbackTimer); };
    document.getElementById("txtFeedback").value = "";
    document.getElementById("btnFeedback").disabled = false;
};

function FeedbackSent(result) {
    document.getElementById("txtFeedback").value = "Thank you";
    _feedbackTimer = window.setTimeout(function() { ClearFeedback(); }, "1500");
};

function SendFeedback(sender) {
    sender.disabled = true;

    var Feedback = document.getElementById("txtFeedback").value;

    if (Feedback.length > 0) {
        Feedback = replace(Feedback, "'", "\'");

        asyncRequest("/feedback.asmx/saveFeedback", '{"Feedback":"' + Feedback + '"}', FeedbackSent);
    };

    return false;
};

window.onerror = function(msg, url, linenumber) {
    asyncRequest("/feedback.asmx/reportError", '{"location":"' + url + '", "err":"' + msg + ', ' + linenumber + '"}');
};


function getCaptionOptions(cat, color, sender) {

    var panel = document.getElementById("pnlMoreOptions");
    document.getElementById("imgDisplay").innerHTML = "Retrieving more options for you...";
    
    if (sender) {
        var caller = document.getElementById(sender);
        var top = left = 0;

        top = caller.parentNode.offsetTop;
        top += caller.parentNode.parentNode.offsetTop;
        top += caller.parentNode.parentNode.parentNode.offsetTop;
        top += 17;

        left = caller.parentNode.offsetLeft;
        left += caller.parentNode.parentNode.offsetLeft;
        left += caller.parentNode.parentNode.parentNode.offsetLeft;
        left -= 202;

        panel.style.top = top + "px";
        panel.style.left = left + "px";
        panel.style.display = "block";
    }
    ;

    var result = syncRequest("/captions.aspx/getOptions", '{"cat":"' + cat + '", "color":"' + color + '"}');

    var json = JSON.parse(result);

    document.getElementById("imgDisplay").innerHTML = json.d;

}
;

function hideCaptionOptionPanel() {
    document.getElementById("pnlMoreOptions").style.display = "none";
    return false;
}
;function movePager(isPrevious, pageIndex) {
    var page = document.getElementById("lblCurrentTopPage").innerHTML;
    var group = document.getElementById("ddlTopCategories");

    if (!isNaN(pageIndex)) {
        page = pageIndex;
    } else {
        if (isPrevious) { page = parseInt(page) - 2 };
    }
    ;

    asyncRequest("comments.aspx/Pager", '{"group":"' + group.options[group.selectedIndex].value + '", "page":"' + page + '"}', PagerSuccess);
}
;

function PagerSuccess(result) {
    var json = JSON.parse(result);

    if (json.d.length == 2) {
        document.getElementById("pnlComments").innerHTML = json.d[0];
        document.getElementById("pnlTopPager").innerHTML = json.d[1];
        document.getElementById("pnlBottomPager").innerHTML = replace(json.d[1], "lblCurrentTopPage", "lblCurrentBottomPage");
    }
    ;
}
;

function syncDDL(sender) {
    var ddl = (sender.id == "ddlTopCategories") ? document.getElementById("ddlBottomCategories") : document.getElementById("ddlTopCategories");
    setDropdownByValue(ddl, sender.options[sender.selectedIndex].value);
    movePager(false, 0);
}
;

function ChangeGroup(group) {
    setDropdownByValue(document.getElementById("ddlBottomCategories"), group)
    if (setDropdownByValue(document.getElementById("ddlTopCategories"), group) > -1) {
        movePager(true, 0);
    };
}
;var _imageArray;
var _runSharedShow = true;
var _currentIndex = 0;
var _displayIndex = 0;
var _timer = -1;

var image1 = new Image();
var image2 = new Image();
var image3 = new Image();
var image4 = new Image();

image1.onload = function() { _timer = window.setTimeout(function() { displayImages(); }, 3000); };
function InitSharingSlideShow() {
    _imageArray = document.getElementById("ctl00_ContentPlaceHolder1_hfFiles").value.split(",");
    preLoadShare();
};

function preLoadShare() {
    var maxPre = 4;
    var useframes = false;

    if (window.location.toString().toLowerCase().indexOf("shareframeslideshow.aspx") > -1) {
        useframes = true;
    };
    
    while (maxPre > 0) {
        if (_currentIndex < _imageArray.length - 1 && _currentIndex >= 0)
        { _currentIndex++; }
        else if (_currentIndex < 0)
        { _currentIndex = _imageArray.length - 1 }
        else { _currentIndex = 0; };
        if (useframes) {
            this["image" + maxPre].src = "/shared/designer.ashx/" + _imageArray[_currentIndex];
        } else {
            this["image" + maxPre].src = "/membersarea/pics/users/" + document.getElementById("ctl00_ContentPlaceHolder1_hfFolder").value + "/originals/" + _imageArray[_currentIndex];
        };
        this["image" + maxPre].Index = _currentIndex;
        maxPre--;
    };
};

function displayImages() {
    var image = null;
    for (var i = 1; i <= 4; i++) {
        image = document.getElementById("image" + i);
        image.src = this["image" + i].src;
        image.setAttribute("Index", this["image" + i].Index);
        image.style.visibility = "visible";
    };

    document.getElementById("ImageUp").style.visibility = "visible";
    document.getElementById("ImageDown").style.visibility = "visible";

    if (image1.onload != null) { image1.onload = null; };

    cycleImages(1);
};

function cycleImages(index) {
    if (_timer != null) { window.clearTimeout(_timer); };
    if (_runSharedShow) {
        var image = null;
        if (index > 4) {
            displayImages();
        } else {
            if (index == 2) { preLoadShare(); };
            _timer = window.setTimeout(function() { cycleImages(index + 1); }, 2000);
            image = document.getElementById("ctl00_ContentPlaceHolder1_imgShared");
            image.setAttribute("title", "Stop Slideshow");
            image.src = document.getElementById("image" + index).src;
        };
    };
};


function pageShared(moveNext) {
    _runSharedShow = false;
    document.getElementById("ctl00_ContentPlaceHolder1_imgShared").setAttribute("title", "Start Slideshow");
    var firstIndex = document.getElementById("image4").getAttribute("Index");
    if (moveNext) {
        _currentIndex = firstIndex + 4;
        preLoadShare();
        displayImages();
    } else {
        _currentIndex = firstIndex - 4;
        preLoadShare();
        displayImages();
    };
};

function loadIntoShare(sender) {
    _runSharedShow = false;
    var image = document.getElementById("ctl00_ContentPlaceHolder1_imgShared");
    image.setAttribute("title", "Start Slideshow");
    image.src = sender.src;
};

function toggleShareShow() {
    _runSharedShow = !_runSharedShow;
    var image = document.getElementById("ctl00_ContentPlaceHolder1_imgShared");
    image.setAttribute("title", (_runSharedShow) ? "Stop Slideshow" : "Start Slideshow");
    if (_runSharedShow) {
        cycleImages(1);
    };

    return false;
};var _totalFiles = 0;
var _completedFiles = 0;

function setTotalFiles(totalFiles) {
    _totalFiles = totalFiles;
    _completedFiles = 0;
    document.getElementById("pnlProgress").style.display = "block";
}
;

function getFileProgress(loaded, total, filename) {
    var percentage = loaded / total * 100;

    var status = document.getElementById("innerProgress");
    var message = document.getElementById("statusMessage");

    var currentFile = parseInt(_completedFiles) + parseInt(1);

    status.style.width = parseInt(percentage) + '%';
    message.innerHTML = "Uploading " + currentFile + " of " + _totalFiles + " (" + parseInt(percentage) + "%)";

    if (percentage == 100) {
        _completedFiles++;

        if (_completedFiles == _totalFiles) {
            document.getElementById("pnlProgress").style.display = "none";

            if (window.location.toString().toLowerCase().indexOf("/myoriginals.aspx") > -1) {
                window.location = window.location.toString();
            };
        };
    };
    
}
;var _isFolders = true;
var _isPhotobucket = false;
var _isMySpace = false;
var _isFacebook = false;

var _currentPath = "";
var _mySpaceURI = "";
function pageFolders(moveNext) {
    var index = (_isFolders) ? document.getElementById("ctl00_ContentPlaceHolder1_hfOriginalPageIndex") : document.getElementById("hfOriginalImageIndex");
    if (!isNaN(index.value)) {
        if (moveNext) { index.value = parseInt(index.value) + 1; } else { index.value = parseInt(index.value) - 1; };
        if (_isFolders) {
            asyncRequest(getWindowLocation() + "/getUserFolders", '{"pageIndex":' + index.value + '}', PageChanged);
        } else {
            if (_isMySpace || _isFacebook) {
                LoadMySpaceImages(index.value);
            } else {
                asyncRequest(getWindowLocation() + "/getUserImages", '{"pageIndex":' + index.value + ', "path":"' + _currentPath + '"}', ImagesChanged);
            };
        };
    }
    ;
}
;

function PageChanged(result) {
    if (window.location.toString().toLowerCase().indexOf("/myoriginals.aspx/") > -1) { restartShow(); };

    var json = JSON.parse(result);

    document.getElementById("originalsContainer").innerHTML = json.d[0];
    document.getElementById("ctl00_ContentPlaceHolder1_hfOriginalPageIndex").value = json.d[1];
}
;

function getPreLoaderLinks() {
    if (document.getElementById("ctl00_ContentPlaceHolder1_hfMySpaceThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = false;
        _isPhotobucket = false;
        _isMySpace = true;

        LoadMySpaceImages(0);
    } else if (document.getElementById("ctl00_ContentPlaceHolder1_hfFacebookThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = true;
        _isPhotobucket = false;
        _isMySpace = false;

        LoadMySpaceImages(0);
    } else if (document.getElementById("ctl00_ContentPlaceHolder1_hfPhotobucketThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = false;
        _isPhotobucket = true;
        _isMySpace = false;

        LoadMySpaceImages(0);
    } else {
        document.getElementById("ActiveFolder").innerHTML = document.getElementById("autoFolder").innerHTML;
        asyncRequest("designer.aspx/getImagesForPreloader", '', startPreloader);
    };
};

function GetMySpaceImages() {
    if (document.getElementById("ctl00_ContentPlaceHolder1_hfMySpaceThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = false;
        _isMySpace = true;
        _isPhotobucket = false;

        LoadMySpaceImages(0);
    } else {
        __doPostBack('ctl00$ContentPlaceHolder1$lbMySpace', '')
    };

    return false;
};

function GetPhotobucketImages() {
    if (document.getElementById("ctl00_ContentPlaceHolder1_hfPhotobucketThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = false;
        _isMySpace = false;
        _isPhotobucket = true;

        LoadMySpaceImages(0);
    } else {
        __doPostBack('ctl00$ContentPlaceHolder1$lbPhotobucket', '')
    };

    return false;
};

function GetFacebookImages() {
    if (document.getElementById("ctl00_ContentPlaceHolder1_hfFacebookThumbs").value.length > 0) {
        _isFolders = false;
        _isFacebook = true;
        _isMySpace = false;
        _isPhotobucket = false;

        LoadMySpaceImages(0);
    } else {
        __doPostBack('ctl00$ContentPlaceHolder1$lbFacebook', '')
    };

    return false;
};

function LoadMySpaceImages(index) {
    document.getElementById("backFolder").style.visibility = "visible";

    var mySpaceImages = null;
    if (_isMySpace) {
        mySpaceImages = document.getElementById("ctl00_ContentPlaceHolder1_hfMySpaceThumbs").value.split(",");
    } else if (_isFacebook) {
        mySpaceImages = document.getElementById("ctl00_ContentPlaceHolder1_hfFacebookThumbs").value.split(",");
    } else {
        mySpaceImages = document.getElementById("ctl00_ContentPlaceHolder1_hfPhotobucketThumbs").value.split(",");
    };
    
    var pageCount = 4;
    var skip = index * pageCount;
    var html = "";

    if (index * pageCount >= mySpaceImages.length - 1) {
        index = 0;
        skip = 0
    }
    else if (index == -1) {
        index = Math.ceil(parseInt(mySpaceImages.length / pageCount));
        skip = index * 4;
    }
    
    document.getElementById("hfOriginalImageIndex").value = index;
    for (var i = skip; i < skip + pageCount; i++) {
        if (i > mySpaceImages.length - 1) { break; };
        html += "<div class=\"cellL trashParent\">";
        html += "<div style=\"height: 110px; overflow: hidden; margin-right: 5px;\">";

        html += "<a href=\"javascript:loadMySpaceImage('";
        html += mySpaceImages[i];
        html += "');\">";

        html += "<img src=\"";
        html += mySpaceImages[i];
        html += "\" style=\"width: 131px;\" />";

        html += "</a>";

        html += "</div>";

        html += "</div>";
    };

    document.getElementById("originalsContainer").innerHTML = html;
};

function loadMySpaceImage(URI, fromRotator) {
    _mySpaceURI = URI;
    if (!fromRotator) {
        document.getElementById("imageTools").style.visibility = "visible";
        document.getElementById("designerTools").style.visibility = "visible";
        if (_frameLoaded) {
            document.getElementById("sharedTools").style.visibility = "visible";
            document.getElementById("GetCode2").style.visibility = "visible";
        };
        _imageLoaded = true;
    };
    document.getElementById("pnlStep").style.backgroundImage = "";
    document["Designer"].loadMySpaceImage(URI, _imgRotation, _blackWhite, fromRotator);    
};

function startPreloader(result) {
    var json = JSON.parse(result);
    preLoaderDesignerImages(0, json.d);
};

function preLoaderDesignerImages(index, links) {
    if (index < links.length) {
        var img = new Image();

        img.src = links[index];

        index++;

        img.onload = function() {
            preLoaderDesignerImages(index, links);
        };
    };
};

function getImages(path) {
    var isDesigner = window.location.toString().toLowerCase().indexOf("/myoriginals.aspx") == -1;
    if (path == null) { path = document.getElementById("ActiveFolder").innerHTML; };
    _currentPath = path;
    _isFolders = false;
    _isMySpace = false;
    _isFacebook = false;
    _isPhotobucket = false;

    document.getElementById("ActiveFolder").innerHTML = path;
    
    document.getElementById("backFolder").style.visibility = "visible";
    
    asyncRequest(getWindowLocation() + "/getUserImages", '{"pageIndex":0, "path":"' + path + '"}', ImagesChanged);
    
    if (!isDesigner) {
        findFolderImages(path);
    }
    ;
}
;

function ImagesChanged(result) {
    var json = JSON.parse(result);

    document.getElementById("originalsContainer").innerHTML = json.d[0];
    document.getElementById("hfOriginalImageIndex").value = json.d[1];
}
;

function backToFolder() {
    var index = document.getElementById("ctl00_ContentPlaceHolder1_hfOriginalPageIndex");
    index.value = parseInt(index.value) + 1;
    _currentPath = "";
    _isFolders = true;
    pageFolders(false);
    
    document.getElementById("backFolder").style.visibility = "hidden";
}
;

function deletefolder(path) {
    if (window.confirm("Are you sure you want to delete " + path + " and all of the pictures in " + path + "?\n\nAny external sites, EG: MySpace, Facebook, that reference pictures and frames in this folder will no longer display them!")) {
        asyncRequest(getWindowLocation() + "/deleteFolder", '{"path":"' + path + '"}', PageChanged);
    };
}
;

function deleteImage(path, image) {
    var isOriginal = window.location.toString().toLowerCase().indexOf("myoriginals.aspx") > -1;
    if (window.confirm("Are you sure you want to delete " + image + "?\n\nAny external sites, EG: MySpace, Facebook, that reference " + image + " will no longer be able to display it!")) {
        asyncRequest(getWindowLocation() + "/deleteImage", '{"path":"' + path + '","image":"' + image + '"}', PageChanged);

        if (isOriginal) {
            _currentPath = path;
            _isFolders = false;
            document.getElementById("ActiveFolder").innerHTML = path;
            document.getElementById("backFolder").style.visibility = "visible";
        };

        if (window.location.toString().toLowerCase().indexOf("/designer.aspx") < 0 && _newWin) { _newWin.close(); };
    } else {
        if (isOriginal) {
            _runSlideShow = true;
            _timerObject = window.setTimeout(function() { MoveSlideShow(); }, 3000);  
        };
    }
    ;
}
;

/* Frame Selectors */

function changeCategory(catID) {
    if (catID) {
        setDropdownByValue(document.getElementById("ddlTopFrameCategories"), catID);
    }
    ;
    moveFrameSelector(1, false);
}
;

function moveFrameSelector(pageIndex, moveNext) {
    var Category = document.getElementById("ddlTopFrameCategories");
    asyncRequest("designer.aspx/MoveFrameSelectors", '{"catID":' + Category.options[Category.selectedIndex].value + ', "pageIndex":' + pageIndex + ', "moveNext":' + moveNext + '}', UpdateFrameSelectors);
}
;

function UpdateFrameSelectors(result) {
    document.getElementById("frameSelectors").innerHTML = JSON.parse(result).d;
}
;

function showNewFolder() {
    document.getElementById("pnlNewFolder").style.display = "block";
    document.getElementById("txtNewFolderName").focus();
}
;

function closeNewAlbum() {
    document.getElementById("pnlNewFolder").style.display = "none";
    document.getElementById("txtNewFolderName").value = "";

    return false;
}
;

function CreateFolder() {
    var FolderName = document.getElementById("txtNewFolderName");
    var result = "";
    if (FolderName.value.length > 0) {
        result = JSON.parse(syncRequest("designer.aspx/FolderExists", '{"FolderName":"' + FolderName.value + '"}'));

        if (result.d.length == 0) {
            getImages(FolderName.value);
            closeNewAlbum();
        } else if (result.d.indexOf("Would you like to open it now") > -1) {
            if (window.confirm(result.d)) {
                getImages(FolderName.value);
                closeNewAlbum();
            } else {
                FolderName.value = "";
            };
        } else {
            alert("Failed to create " + FolderName.value);
        };
    } else {
        alert("Please type your new folder's name.");
        FolderName.focus();
    }
    ;
}
;

function loadFrameFromSelector(ColorID, GroupID) {
    _groupID = GroupID;
    _colorID = ColorID;
    asyncRequest("designer.aspx/GetColorOptions", '{"groupID":' + GroupID + '}', FrameColorsLoaded);
    
    
}
;

function FrameColorsLoaded(result) {
    document.getElementById("pnlFrameColors").innerHTML = JSON.parse(result).d;
    LoadFrame();
}
;

/* Image Uploader */

function getUploadParameters() {
    var params = "?f=" + document.getElementById("ActiveFolder").innerHTML + "&AUTHID=" + document.getElementById("ctl00_ContentPlaceHolder1_hfName").value;
    return params;
};

function debug(data) { alert(data); };

/* Designer */
var _frameLoaded = false;
var _isLandscape = true;
var _colorID = -1;
var _groupID = -1;
var _locked = false;

var _imageLoaded = false;
var _imgName = "";
var _imgPath = "";
var _currentAction = "";
var _imgRotation = 0;
var _blackWhite = false;

//var scrollTop = document.body.scrollTop
//    ? document.body.scrollTop
//    : (window.pageYOffset
//        ? window.pageYOffset
//        : (document.body.parentElement
//            ? document.body.parentElement.scrollTop
//            : 0
//        )
//    );

function LoadFrame() {
    document.getElementById("frameTools").style.visibility = "visible";
    document.getElementById("designerTools").style.visibility = "visible";
    if (_imageLoaded) {
        document.getElementById("sharedTools").style.visibility = "visible";
        document.getElementById("GetCode2").style.visibility = "visible";
    };
    _frameLoaded = true;
    document.getElementById("pnlStep").style.backgroundImage = "";
    document["Designer"].loadFrame(_groupID , _colorID , _isLandscape);
}
;

function LoadImage(path, file) {
    _imgName = file;
    _imgPath = path;
    window.scroll(0, 442);
    LoadFlashImage();
}
;

function LoadFlashImage(fromRotator) {
    if (!fromRotator) {
        document.getElementById("imageTools").style.visibility = "visible";
        document.getElementById("designerTools").style.visibility = "visible";
        if (_frameLoaded) {
            document.getElementById("sharedTools").style.visibility = "visible";
            document.getElementById("GetCode2").style.visibility = "visible";
        };
        _imageLoaded = true;
    };
    document.getElementById("pnlStep").style.backgroundImage = "";
    document["Designer"].loadImage(_imgPath, _imgName, _imgRotation, _blackWhite, fromRotator);
};

function lockControl() {
    var Lock = document.getElementById("Lock");
    if (_locked) {
        document.getElementById("RotateFrame").style.visibility = "visible";
        document.getElementById("ImageLeft").style.visibility = "visible";
        document.getElementById("ImageRight").style.visibility = "visible";
        document.getElementById("ImageUp").style.visibility = "visible";
        document.getElementById("ImageDown").style.visibility = "visible";
        document.getElementById("EnlargeImage").style.visibility = "visible";
        document.getElementById("ShrinkImage").style.visibility = "visible";
        document.getElementById("RotateImageRight").style.visibility = "visible";
        document.getElementById("RotateImageLeft").style.visibility = "visible";

        Lock.setAttribute("title", "Lock");
        Lock.style.backgroundPosition = "-139px -284px";
        _locked = false;
    } else {
        document.getElementById("RotateFrame").style.visibility = "hidden";
        document.getElementById("ImageLeft").style.visibility = "hidden";
        document.getElementById("ImageRight").style.visibility = "hidden";
        document.getElementById("ImageUp").style.visibility = "hidden";
        document.getElementById("ImageDown").style.visibility = "hidden";
        document.getElementById("EnlargeImage").style.visibility = "hidden";
        document.getElementById("ShrinkImage").style.visibility = "hidden";
        document.getElementById("RotateImageRight").style.visibility = "hidden";
        document.getElementById("RotateImageLeft").style.visibility = "hidden";

        Lock.setAttribute("title", "Unlock");
        Lock.style.backgroundPosition = "-139px -508px";
        _locked = true;
    };

    document["Designer"].setLock();
};

function changeFrameColor(colorID) {
    _colorID = colorID;
    LoadFrame();
}
;

function rotateFrame() {
    _isLandscape = !_isLandscape;
    LoadFrame();
}
;

function rotateImage(isClockwise) {
    switch (_imgRotation) {
        case 0:
            _imgRotation = (isClockwise) ? 90 : 270;
            break;
        case 90:
            _imgRotation = (isClockwise) ? 180 : 0;
            break;
        case 180:
            _imgRotation = (isClockwise) ? 270 : 90;
            break;
        case 270:
            _imgRotation = (isClockwise) ? 0 : 180;
            break;
        default: break;
    };

    if (_isMySpace || _isFacebook) {
        loadMySpaceImage(_mySpaceURI, true);
    } else {
        LoadFlashImage(true);
    };
}
;

function setBlackWhite() {
    var sender = document.getElementById("ImageColorMode")
    if (_blackWhite) {
        _blackWhite = false;
        sender.style.backgroundPosition = "-90px -172px";
        sender.setAttribute("title", "Change to Grayscale");
    } else {
        _blackWhite = true;
        sender.style.backgroundPosition = "-90px -116px"
        sender.setAttribute("title", "Change to Color");
    };
    if (_isMySpace || _isFacebook) {
        loadMySpaceImage(_mySpaceURI, true);
    } else {
        LoadFlashImage(true);
    }
}
;

function sendAction(action, fromFlash) {
    var sender = null;
    switch (action) {
        case "sf": /* Shrink Frame*/
            sender = document.getElementById("ShrinkFrame")
            break;
        case "ef": /* Enlarge Frame*/
            sender = document.getElementById("EnlargeFrame")
            break;
        case "il": /* Move Image Left*/
            sender = document.getElementById("ImageLeft")
            break;
        case "ir": /*Move Image Right*/
            sender = document.getElementById("ImageRight")
            break;
        case "iu": /* Move Image Up*/
            sender = document.getElementById("ImageUp")
            break;
        case "id": /* Move Image Down*/
            sender = document.getElementById("ImageDown")
            break;
        case "si": /* Shrink Image*/
            sender = document.getElementById("ShrinkImage")
            break;
        case "ei": /* Enlarge Image*/
            sender = document.getElementById("EnlargeImage")
            break;
        default: break;
    };
    if (action == _currentAction || fromFlash) { action = ""; };
    _currentAction = action;

    document["Designer"].sendAction(action);
    
    var actionControls = [document.getElementById("ShrinkFrame"), document.getElementById("EnlargeFrame"), document.getElementById("ImageLeft"), document.getElementById("ImageRight"),
                          document.getElementById("ImageUp"), document.getElementById("ImageDown"), document.getElementById("ShrinkImage"), document.getElementById("EnlargeImage")];
    var normalPosition = ["-139px -228px", "-90px -228px", "-90px -340px", "-139px -340px", "-90px -396px", "-139px -396px", "-139px -4px", "-90px -4px"];
    var stopSignPosition = "-139px -172px";
    
    for (var i = 0; i < actionControls.length; i++) {
        if (actionControls[i] == sender) {
            sender.style.backgroundPosition = (action.length > 0) ? stopSignPosition : normalPosition[i];
        } else {
            actionControls[i].style.backgroundPosition = normalPosition[i];
        }
        ;
    };       
}
;

function changeFrameRotation(isLandscape, frameLoaded) {
    if (isLandscape != _isLandscape && frameLoaded) {
        rotateFrame();
    };
}
;

function getDesignCode() {
    var Info = null;
    var result = null;
    if (_isMySpace) {
        _imgPath = "MySpace";
        _imgName = _mySpaceURI;
    } else if (_isFacebook) {
        _imgPath = "Facebook";
        _imgName = _mySpaceURI;
    } else if (_isPhotobucket) {
        _imgPath = "Photobucket";
        _imgName = _mySpaceURI;
    };

    if (_frameLoaded) {
        Info = JSON.parse(document["Designer"].getFrameInfo()).DesignInfo;
        if (!_imgName || _imgName == "undefined" || _imgName.length == 0) {
            asyncRequest("/feedback.asmx/reportError", '{"location":"' + window.location + '", "err":"Javascript: Failed to set ImgName"}');
        };
        result = syncRequest("designer.aspx/SaveDesign", '{"groupID":' + _groupID + ',"colorID":' + _colorID + ',"isLandscape":' + _isLandscape + ', "frameWidth":' + Info.frameWidth + ', "frameHeight":' + Info.frameHeight + ', "imageWidth":' + Info.imageWidth + ', "imageHeight":' + Info.imageHeight + ', "x":' + parseInt(Math.round(Info.imageX)) + ', "y":' + parseInt(Math.round(Info.imageY)) + ', "rotation":' + _imgRotation + ', "blackWhite":' + _blackWhite + ', "imageFolder":"' + _imgPath + '", "imageName":"' + _imgName + '"}');
        
        window.location = "/getcode/designerstuff.aspx/" + JSON.parse(result).d;
    } else {
        Info = JSON.parse(document["Designer"].getImageInfo()).ImageInfo;
        result = JSON.parse(syncRequest("myoriginals.aspx/saveImageChanges", '{"Width":' + Info.Width + ', "Height":' + Info.Height + ', "BlackWhite":' + _blackWhite + ', "Rotation":' + _imgRotation + ', "FolderName":"' + _imgPath + '", "ImageName":"' + _imgName + '"}'));

        window.location = "/getcode/originals.aspx/" + result.d;
    }
    ;
}
;


function setInputBounds(Width, Height) {
    document.getElementById("txtImageWidth").value = Width;
    document.getElementById("txtImageHeight").value = Height;
};

function fireDesignSizeChange(event) {
    if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
        event.srcElement.blur();
        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();
        return false;
    };
    return true;
};

function sendSizeChange(value, isWidth) {
    document["Designer"].sendSizeChange(value, isWidth);
};
var _slideShow = null;
var _runSlideShow = false;
var _index = -1;
var _timerObject;

var _width = _height = 0;

function loadImageData() {
    var img = new Image();
    
    img.src = _slideShow.d[_index];

    img.onload = function() {
        document.getElementById("txtImageWidth").value = img.width;
        document.getElementById("txtImageHeight").value = img.height;
        _width = img.width;
    };

    var domImg = document.getElementById("imgSlider");
    domImg.src = img.src;
    domImg.style.visibility = "visible";
    
    document.getElementById("currentImagePage").value = _index + 1;
    document.getElementById("txtImageWidth").value = img.width;
    document.getElementById("txtImageHeight").value = img.height;
    _width = img.width;
    _height = img.height;
}
;

function InitializeShow() {
    if (parseInt(document.getElementById("totalEdits").value) > 0) {
        document.getElementById("ImageUp").style.visibility = "visible";
        document.getElementById("ImageDown").style.visibility = "visible";
    }
    ;
    asyncRequest("myoriginals.aspx/getSlideShowList", '', ImageCollected);
}
;

function restartShow() {
    _index = (_index == 0) ? _slideShow.d.length - 1 : _index - 1;
    InitializeShow();
}
;


function preLoadImages(loaderIndex) {
    if (loaderIndex < _slideShow.d.length) {
        var img = new Image();

        img.src = _slideShow.d[loaderIndex];

        loaderIndex++;

        img.onload = function() {
            preLoadImages(loaderIndex);
        };
    };
};

function ImageCollected(result) {
    _slideShow = JSON.parse(result);

    if (_slideShow.d.length > 0) {
        preLoadImages(0);
    
        document.getElementById("totalImages").innerHTML = _slideShow.d.length;

        document.getElementById("pnlImageControls").style.visibility = "visible";
        document.getElementById("trashIt").style.visibility = "visible";

        var stopper = document.getElementById("ImageStopPlay");

        if (_slideShow.d.length > 1) {
            stopper.setAttribute("title", "Stop Slideshow");
            stopper.style.backgroundPosition = "-90px -452px";
            _runSlideShow = true;
        } else {
            stopper.setAttribute("title", "Start Slideshow");
            stopper.style.backgroundPosition = "-139px -452px";
            _runSlideShow = false;
            _index = 0;
            loadImageData();
        };

        MoveSlideShow();

        _bw = false;
        _rotation = 0;
    };
}
;

function MoveSlideShow() {
    var stopper = document.getElementById("ImageStopPlay");
    if (_timerObject) { window.clearTimeout(_timerObject); };
    if (_runSlideShow) {
        stopper.setAttribute("title", "Stop Slideshow");
        stopper.style.backgroundPosition = "-90px -452px";
        
        var sender = document.getElementById("ImageColorMode")
        sender.style.backgroundPosition = "-90px -172px";
        sender.setAttribute("title", "Grayscale");

        _index = (_index >= _slideShow.d.length - 1) ? 0 : _index + 1;

        loadImageData();

        _timerObject = window.setTimeout(function() { MoveSlideShow(); }, 3000);
    } else {
        stopper.setAttribute("title", "Start Slideshow");
        stopper.style.backgroundPosition = "-139px -452px";
    };
}
;

function toggleSlideShow() {
    var stopper = document.getElementById("ImageStopPlay");
    if (_runSlideShow) {
        stopper.setAttribute("title", "Start Slideshow");
        stopper.style.backgroundPosition = "-139px -452px";
        _runSlideShow = false;
    } else {
        stopper.setAttribute("title", "Stop Slideshow");
        stopper.style.backgroundPosition = "-90px -452px";
        _runSlideShow = true;
        _index--;
        _bw = false;
        _rotation = 0;
        MoveSlideShow();
    };
}
;

function pageSlideShow(moveNext) {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;

    if (moveNext) {
        _index = (_index >= _slideShow.d.length - 1) ? 0 : _index + 1;
    } else {
        _index = (_index == 0) ? _slideShow.d.length - 1 : _index - 1;
    }
    ;
    
    loadImageData();
}
;

function loadOriginalImage(path, file) {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    for (var i = 0; i < _slideShow.d.length; i++) {
        if (_slideShow.d[i].indexOf(file) > -1 && _slideShow.d[i].indexOf(path) > -1) {
            _index = i;
            loadImageData();
            break;
        }
        ;
    };
}
;

function fireGoToImage(event) {
    if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
        goToImage();
    };
};

function findFolderImages(path) {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    if (_timerObject) { window.clearTimeout(_timerObject); };

    path = "/" + path.toLowerCase() + "/";

    for (var i = 0; i < _slideShow.d.length; i++) {
        if (_slideShow.d[i].indexOf(path) > -1) {
            _index = i;
            loadImageData();
            break;
        }
        ;
    };

    _bw = false;
    _rotation = 0;
    stopper.setAttribute("title", "Stop Slideshow");
    stopper.style.backgroundPosition = "-90px -452px";
    _runSlideShow = true;
    _timerObject = window.setTimeout(function() { MoveSlideShow(); }, 3000);
}
;

function goToImage() {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    var page = document.getElementById("currentImagePage").value;
    if (page > _slideShow.d.length) { page = _slideShow.d.length; }
    else if (page < 1) { page = 1; };
    
    _index = page - 1;
    loadImageData();
}
;

function fireSizeChange(event) {
    if (event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
        sizeChange();
        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();
        return false;
    };
    return true;
};

function sizeChange() {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;

    var Width = document.getElementById("txtImageWidth");
    var Height = document.getElementById("txtImageHeight");

    if (!isNaN(Width.value) && !isNaN(Height.value)) {
        var ratio = 0;
        var maxSize = 378;
        if (parseInt(Width.value) == _width) {
            if (_height > _width) { maxSize = 504 };
            if (parseInt(Height.value) < 100) {
                Height.value = 100;
            } else if (parseInt(Height.value) > maxSize) {
                Height.value = maxSize;
            }
            ;
        
            ratio = parseFloat(Height.value) / parseFloat(_height);
            Width.value = parseInt(_width * ratio);
        }
        else {
            if (_width > _height) { maxSize = 504 };
            if (parseInt(Width.value) < 100) {
                Width.value = 100;
            } else if (parseInt(Width.value) > maxSize) {
                Width.value = maxSize;
            }
            ;
        
            ratio = parseFloat(Width.value) / parseFloat(_width);
            Height.value = parseInt(_height * ratio);
        };
        _height = Height.value;
        _width = Width.value;
        _maxsize = (_width > _height) ? _width : _height;

        getEditSrc();        
    } else {
        Width.value = _width;
        Height.value = _height;
    }
    ;
}
;

function getImageDeleteParams() {
    if (_timerObject) { window.clearTimeout(_timerObject); };
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    var imageToDelete = _slideShow.d[_index];

    file = imageToDelete.substr(imageToDelete.lastIndexOf(".ashx/") + 6).split("/");

    deleteImage(file[0], file[1]);
}
;

var _rotation = 0;
var _maxsize = 504;
var _bw = false;
function changeToBlackWhite() {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    var sender = document.getElementById("ImageColorMode")

    if (_bw) {
        sender.style.backgroundPosition = "-90px -172px";
        sender.setAttribute("title", "Grayscale");
        _bw = false;
    } else {
        sender.style.backgroundPosition = "-90px -116px";
        sender.setAttribute("title", "Color");
        _bw = true;
    }
    ;
    getEditSrc();
}
;

function rotateOriginal(clockwise) {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    switch (_rotation) {
        case 0:
            _rotation = (clockwise) ? 90 : 270;
            break;
        case 90:
            _rotation = (clockwise) ? 180 : 0;
            break;
        case 180:
            _rotation = (clockwise) ? 270: 90;
            break;
        case 270:
            _rotation = (clockwise) ? 0: 180;
            break;
        default:
            _rotation = 0;
            break;
    }
    ;
    getEditSrc();
}
;

function getEditSrc() {
    document.getElementById("imgSlider").src = _slideShow.d[_index] + "/" + _maxsize.toString() + "/" + _bw.toString() + "/" + _rotation.toString();
}
;

function getOriginalCode() {
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";
    _runSlideShow = false;
    var imageToDelete = _slideShow.d[_index];

    file = imageToDelete.substr(imageToDelete.lastIndexOf(".ashx/") + 6).split("/");

    var json = JSON.parse(syncRequest("myoriginals.aspx/saveImageChanges", '{"Width":' + _width + ', "Height":' + _height + ', "BlackWhite":' + _bw + ', "Rotation":' + _rotation + ', "FolderName":"' + file[0] + '", "ImageName":"' + file[1] + '"}'));

    window.location = "/getcode/originals.aspx/" + json.d;
}
;

function pageEdit(moveNext) {
    var PageIndex = document.getElementById("editIndex").value;

    if (!isNaN(PageIndex)) {
        PageIndex = (moveNext) ? parseInt(PageIndex) + 1 : parseInt(PageIndex) - 1;        
    } else {
        PageIndex = 0;
    }
    ;

    asyncRequest("myoriginals.aspx/pageEdits", '{"pageIndex":' + PageIndex + '}', EditsPaged);
}
;

function EditsPaged(result) {
    document.getElementById("edits").innerHTML = JSON.parse(result).d;

    if (parseInt(document.getElementById("totalEdits").value) == 0) {
        document.getElementById("ImageUp").style.visibility = "hidden";
        document.getElementById("ImageDown").style.visibility = "hidden";
    }
    ;
}
;

function deleteEditImage(picture) {
    if (window.confirm("Are you sure you want to delete this image?\n\nAny external sites, EG: MySpace, Facebook, that reference this image will no longer be able to display it!")) {
        var PageIndex = document.getElementById("editIndex").value;

        asyncRequest("myoriginals.aspx/deleteEdittedImage", '{"pageIndex":' + PageIndex + ', "pictureID":"' + picture + '"}', EditsPaged);
    };
}function getAvatarUpload() {
    var frame = window.frames['iAvatarUpload'];
    var hasFile = frame.document.getElementById("hfIsComplete");

    if (hasFile.value == "true") {
        
        var filePath = frame.document.getElementById("hfAvatarPath").value;
        var errorMsg = frame.document.getElementById("hfErrorMessage").value;
        var image = document.getElementById("ctl00_ContentPlaceHolder1_avatar");
        var masterImage = document.getElementById("ctl00_imgAvatar");
        if (errorMsg.length > 0) {
            alert(errorMsg);
        } else {
            image.src = filePath;
            image.style.visibility = "visible";
            if (masterImage) {
                masterImage.src = filePath;
            };
        };
    };
};var _currentFolder = "";
var _myFramesList = null;
var _myFramePreLoad = new Image();
var _myFrameTimer = null;
var _runMyFrameShow = true;
var _myFrameIndex = 0
var _isMyFrameFolder = true;

function stopMyFrameShow() {
    _runMyFrameShow = false;
    var stopper = document.getElementById("ImageStopPlay");
    
    stopper.setAttribute("title", "Start Slideshow");
    stopper.style.backgroundPosition = "-139px -452px";

    document.getElementById("imgSlider").setAttribute("title", "Start Slideshow");
}
;

function startMyFrameShow() {
    _runMyFrameShow = true;
    var stopper = document.getElementById("ImageStopPlay");
    stopper.setAttribute("title", "Stop Slideshow");
    stopper.style.backgroundPosition = "-90px -452px";
    
    document.getElementById("imgSlider").setAttribute("title", "Stop Slideshow");
    _myFrameTimer = window.setTimeout(function() { cycleMyFrames(); }, 2500);
}
;

function getFramedImages(folderName) {
    _isMyFrameFolder = false;
    _currentFolder = folderName;
    asyncRequest("myframes.aspx/getFramedImages", '{"pageIndex":0, "path":"' + folderName + '"}', FramedImagesCompleted);
}
;
function FramedImagesCompleted(framedImages) {
    var frames = JSON.parse(framedImages);
    document.getElementById("originalsContainer").innerHTML = frames.d[0];
    document.getElementById("hfPageIndex").value = frames.d[1];
    document.getElementById("backFolder").style.visibility = "visible";
}
;
function BackToMyFramesFolders() {
    _isMyFrameFolder = true;
    asyncRequest("myframes.aspx/getUserFolders", '{"pageIndex":0}', FoldersPaged);
    document.getElementById("backFolder").style.visibility = "hidden";
}
;

function cycleMyFrames(forceCycle) {
    if (_myFrameTimer) { window.clearTimeout(_myFrameTimer); };
    if (_runMyFrameShow || forceCycle) {
        var img = document.getElementById("imgSlider");

        img.src = _myFramesList[_myFrameIndex];

        if (_myFrameIndex < _myFramesList.length - 1) { _myFrameIndex++; } else { _myFrameIndex = 0 };

        _myFramePreLoad.src = _myFramesList[_myFrameIndex];
        img.style.visibility = "visible";

        if (_myFramesList.length > 1) {
            _myFrameTimer = window.setTimeout(function() { cycleMyFrames(); }, 2500);
        }
    }
}
;

function FrameListCompleted(result) {
    _myFramesList = JSON.parse(result).d;
    _myFrameIndex = 0;

    startMyFrameShow();
}
;

function deleteMyFrame(path, image) {
    if (window.confirm("Are you sure you want to delete this image?\n\nAny external sites, EG: MySpace, Facebook, that reference this image will no longer be able to display it!")) {
        var j = JSON.parse(syncRequest("myframes.aspx/deleteMyFrame", '{"path":"' + path + '", "image":"' + image + '"}')).d;

        document.getElementById("originalsContainer").innerHTML = j;

        asyncRequest("myframes.aspx/getSlideShowList", '', FrameListCompleted);
    };
};

function InitMyFrames() {
    asyncRequest("myframes.aspx/getSlideShowList", '', FrameListCompleted);

};

function toggleMyFrameShow() {
    if (!_runMyFrameShow) {
        startMyFrameShow();
    } else {
        stopMyFrameShow();
    };
}
;

function pageMyFrames(moveNext) {
    var index = document.getElementById("hfPageIndex").value;

    if (isNaN(index)) { index = 0; };
    if (moveNext) { index++; } else { index--; };

    if (_isMyFrameFolder) {
        asyncRequest("myframes.aspx/getUserFolders", '{"pageIndex":' + index + '}', FoldersPaged); 
    } else {
        asyncRequest("myframes.aspx/getFramedImages", '{"pageIndex":' + index + ', "path":"' + _currentFolder + '"}', FramedImagesCompleted);
    };
};

function FoldersPaged(result) {
    var folders = JSON.parse(result);
    document.getElementById("originalsContainer").innerHTML = folders.d[0];
    document.getElementById("hfPageIndex").value = folders.d[1];
};

function deleteMyFrameFolder(folder) {
    if (window.confirm("Are you sure you want to delete " + folder + " and all of the framed pictures in " + folder + "?\n\nAny external sites, EG: MySpace, Facebook, that reference frames in this folder will no longer display them!")) {
        syncRequest("myframes.aspx/deleteMyFolder", '{"path":"' + folder + '"}');

        window.location = "myframes.aspx";
    };
}
;

function pageMyFrameShow(moveNext) {

    if (!moveNext) {
        _myFrameIndex = _myFrameIndex - 2;

        if (_myFrameIndex < 0) {
            _myFrameIndex = _myFramesList.length - 3;
        };
    };

    cycleMyFrames(true);
    stopMyFrameShow();
}
;

function loadImage(imageID) {;
    var frameListID;
    
    for (var i = 0; i < _myFramesList.length; i++) {
        frameListID = _myFramesList[i].substr(_myFramesList[i].indexOf(".ashx/") + 6, 36);

        if (frameListID == imageID) {
            _myFrameIndex = i;
            cycleMyFrames(true);
            stopMyFrameShow();
            return;
        };
    };
};