// common scripting for all the pages

// setup the form saver
// triggered by anything that has the form_saver class assigned
$(document).ready(function() {
    $(".form_saver").unbind("click").click(function(e) {
        e.preventDefault();

        var handlerType = $(this).attr("handler_type");
        if (handlerType == "") {
            alert("Please specify the handler_type.");
        }

        var validator = $(this).attr("validator");
        var onsuccess = $(this).attr("onsuccess");
        var onfailed = $(this).attr("onfailed");

        if (!eval(validator)) {
            // validation failed, exit
            return;
        }

        var encodedFormData = $("#aspnetForm").serialize();

        $.post("/Ajax/SaveFormData.aspx", { ft: handlerType, dt: encodedFormData }, function(xml) {
            if ($("messages", xml).text() != "") {
                //alert($("messages", xml).text());
                eval(onfailed);
            }

            eval(onsuccess);
        });

    });
});

function loadControl(name, library) {
    if ($("#" + name).length == 0) {
        return false;
    }

    var segmentType = "";

    if (typeof this["segment"] !== 'undefined')
        segmentType = segment;

    var environmentType = "";

    if (typeof this["environment"] !== 'undefined')
        environmentType = environment;

    $.post("/Ajax/LoadControl.aspx", { cid: name, dt: library, st: segmentType, env: environmentType }, function(xml) {
        $("#" + name).html($("html", xml).text());

        if (typeof sIFRReplace == 'function') {

            sIFRReplace();
        }

        if ($("messages", xml).text() != "") {
            alert($("messages", xml).text());
        }
    });

    return false;
}

// preload images

jQuery.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

$.preloadImages(
    "/gtcentral-images/pre/nav_top/tab8_on.gif",
    "/gtcentral-images/pre/nav_top/tab2_on.gif",
    "/gtcentral-images/pre/nav_top/tab3_on.gif",
    "/gtcentral-images/pre/nav_top/tab4_on.gif",
    "/gtcentral-images/pre/nav_top/tab5_on.gif",
    "/gtcentral-images/pre/nav_top/tab6_on.gif",
    "/gtcentral-images/pre/nav_top/tab7_on.gif");


// post it notes stuff
var postItTop = 200;
var postItLeft = 200;
var postItOpen = "false";
var postItNote = "Your note here...";

var openSpeed = 200;

$(document).ready(function() {
    //setupPostItNote();
});

function setupPostItNote() {
    // create the postIt button in the header
    $.post("/Ajax/PostItNote.aspx", { t: postItTop, l: postItLeft, o: postItOpen, n: postItNote, a: "Get" }, function(xml) {

        // set the data as we got it
        postItTop = $("top", xml).text();
        postItLeft = $("left", xml).text();
        postItOpen = $("open", xml).text();
        postItNote = $("note", xml).text();

        $("div:first").append("<div id='postItButton'><img src='/images/ee_logo.gif' width='40px' height='40px' border='0'/></div><div id='postIt'><div id='postItContent'><textarea cols='20' rows='7' class='sticky' id='postItTextArea'>" + postItNote + "</textarea></div></div>");

        $("#postIt").css("top", postItTop);
        $("#postIt").css("left", postItLeft);

        repositionPostItButton();

        window.onresize = repositionPostItButton;

        // TODO: implement dragging only for the proper areas        
        $("#postIt").draggable({
            stop: function() {
                postItTop = $("#postIt").offset().top;
                postItLeft = $("#postIt").offset().left;

                saveToServer();
            }
        });

        if (postItOpen == "true") {
            animatePostIt(postItOpen);
        }

        $("#postItButton").click(function() {
            togglePostIt();
        });

        $("#postItTextArea").keyup(function() {
            postItNote = $("#postItTextArea").attr("value");

            // queue a save          
            window.setTimeout("saveToServer()", 2000);
        })


    });
}

function animatePostIt(open) {

    if (open == "true") {
        // animate opening

        $("#postIt").css("top", $("#postItButton").offset().top);
        $("#postIt").css("left", $("#postItButton").offset().left);
        $("#postIt").css("width", $("#postItButton").width());
        $("#postIt").css("height", $("#postItButton").height());

        $("#postIt").show();

        $("#postIt").animate({
            top: postItTop,
            left: postItLeft,
            width: 320,
            height: 320
        }, openSpeed);

    }

    else {
        // animate closing

        $("#postIt").animate({
            top: $("#postItButton").offset().top,
            left: $("#postItButton").offset().left,
            width: $("#postItButton").width(),
            height: $("#postItButton").height()
        }, openSpeed, "", function() {
            $("#postIt").hide();
        });
    }
}

function togglePostIt() {
    if (postItOpen == "true") {
        postItOpen = "false";

        saveToServer();
    }
    else {
        postItOpen = "true";

        saveToServer();
    }

    animatePostIt(postItOpen);

}

function repositionPostItButton() {
    if ($("#cartdisplaywrapper[name='cartdisplaywrapper']").length > 0) {
        $("#postItButton").css("top", $("#cartdisplaywrapper").offset().top - 10);
        $("#postItButton").css("left", $("#cartdisplaywrapper").offset().left - 120);
    }
}

function saveToServer() {
    $.post("/Ajax/PostItNote.aspx", { t: postItTop, l: postItLeft, o: postItOpen, n: postItNote, a: "Set" });
}



//-------------------------------------------------------------------------------------------------------
// ClearTypeFadeTo / ClearTypeFadeIn / ClearTypeFadeOut
//
// Custom fade in and fade out functions for jQuery that will work around
// IE's bug with bold text in elements that have opacity filters set when
// also using Window's ClearType text rendering.
//
// New Parameter:
// bgColor    The color to set the background if none specified in the CSS (default is '#fff')
//
// Examples:
// $('div').ClearTypeFadeIn({ speed: 1500 });
// $('div').ClearTypeFadeIn({ speed: 1500, bgColor: '#ff6666', callback: myCallback });
// $('div').ClearTypeFadeOut({ speed: 1500, callback: function() { alert('Fade Out complete') } });
//
// Notes on the interaction of ClearType with DXTransforms in IE7
// http://blogs.msdn.com/ie/archive/2006/08/31/730887.aspx
(function($) {
    $.fn.ClearTypeFadeTo = function(options) {
        if (options)
            $(this)
				.show()
				.each(function() {
				    if (jQuery.browser.msie) {
				        // Save the original background color
				        $(this).attr('oBgColor', $(this).css('background-color'));
				        // Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text)
				        $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
				    }
				})
				.fadeTo(options.speed, options.opacity, function() {
				    if (jQuery.browser.msie) {
				        // ClearType can only be turned back on if this is a full fade in or
				        // fade out. Partial opacity will still have the problem because the
				        // filter style must remain. So, in the latter case, we will leave the
				        // background color and 'filter' style in place.
				        if (options.opacity == 0 || options.opacity == 1) {
				            // Reset the background color if we saved it previously
				            $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
				            // Remove the 'filter' style to restore ClearType functionality.
				            $(this).get(0).style.removeAttribute('filter');
				        }
				    }
				    if (options.callback != undefined) options.callback();
				});
    };

    $.fn.ClearTypeFadeIn = function(options) {
        if (options)
            $(this)
				.css({ opacity: 0 })
				.ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
    };

    $.fn.ClearTypeFadeOut = function(options) {
        if (options)
            $(this)
				.css({ opacity: 1 })
				.ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
    };
})(jQuery);

// Parse strings looking for color tuples [255,255,255]
// transform the color attribute view from the format used by various browsers into an array
function getRGB(color) {
    var result;

    // Check if we're already dealing with an array of colors
    if (color && color.constructor == Array && color.length == 3)
        return color;

    // Look for rgb(num,num,num)
    if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
        return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

    // Look for rgb(num%,num%,num%)
    if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
        return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];

    // Look for #a0b1c2
    if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
        return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];

    // Look for #fff
    if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
        return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];

    // Otherwise, we're most likely dealing with a named color
    return colors[jQuery.trim(color).toLowerCase()];
}

