$(function() {
    if (typeof($.fn.qtip) != 'undefined') {
        $('a.tip[title]').qtip({
            style: {
                name: 'cream',
                tip: true
            },
            position: {
                corner: {
                   target: 'rightMiddle',
                   tooltip: 'leftMiddle'
                }
             }
        });
    }


    $("a.deleteConfirm").click(function(e) {
        e.preventDefault();
        e.stopPropagation();

        return confirm($(this).attr("rel"));
    });

    $("input[type=image][name=do_save]").hover(
        function() {
            $(this).attr("src", "/images/button-save-over.png");
        }, function() {
            $(this).attr("src", "/images/button-save.png");
        }
    );

    $("input[type=image][name=do_next]").hover(
            function() {
                $(this).attr("src", "/images/button-save-continue-over.png");
            }, function() {
                $(this).attr("src", "/images/button-save-continue.png");
            }
        );

    $(".contentContainer:not(.noShadow)").wrap('<div class="contentContainerShadow"></div>');

    $('a.viewLinks').each(function(i) {
        $(this).attr("rel", i).click(function() {
            $(".viewLinksWrapper:eq(" + $(this).attr("rel") + ")").fadeToggle();
        });
    });

    $("a.spriteButtons.design, a.spriteButtons.edit").click(function(e) {
        e.preventDefault();

        if ("Active" == $(".promotionStatusValue" + $(this).attr("rel")).text()) {
            if (!confirm("Are you sure you want to edit this active promotion?")) {
                return false;
            }
        }

        location.href = $(this).attr("href");
    });

    $("a.launchStatus").each(function() {
        $(this).colorbox({
            href: $(this).attr("rel"),
            transition: "none",
            fixedHeight: 480,
            fixedWidth: 530
        });
    });
});

// add more file fields for attachments
function addField (elem) {
    $("#sortable").append('<li class="ui-state-default">some code here - <a href="#" onClick="removeField(this); return false;">remove</a></li>');
};

// remove file fields for attachments
function removeField (elem) {
    $(elem).parent('li').remove();
};


function alertObject(obj) {
    var s = "";
    for (myKey in obj){
        if (myKey != 'outerText' && myKey != 'outerHTML' && myKey != 'innerHTML' && myKey != 'innerText') {
            s += ("myObj["+myKey +"] = "+obj[myKey]) + "\r\n";
        }
    }
    alert(s);
}

// fade in/out control
function fadeToggle(ID) {
    var elem =  document.getElementById(ID);
    if(elem.style.display == 'none') {
        $("#" + ID).fadeIn("normal");
    } else {
        $("#" + ID).fadeOut("normal");
    }
};

// fade in/out control
function fadeToggleStats(ID) {
    var elem =  $("#"+ID);
    var p =  elem.parent();
    if(elem.css("display") != 'block') {
        p.find(".fadeDiv").slideDown("normal");
        p.find("a.viewDetails").html('Hide Quick Stats');
        p.find("a.viewDetails").addClass('open');
    } else {
        p.find(".fadeDiv").slideUp("normal");
        p.find("a.viewDetails").html('Show Quick Stats');
        p.find("a.viewDetails").removeClass('open');
    }
};



function swap(ID) {
// swaps tabs
    $(".tabDiv .close").hide();
    $(".tabs a").removeClass("selected");
    $("#"+ ID).fadeIn("fast");
    $("#"+ "a" + ID).addClass("selected");

    return true;
};


function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}


function createJSInclusion(src) {
    return '<script type="text/javascript" src="' + src +  '"></script>';
}



// new additions for V2


$(document).ready(function() {


// for buttons, wraps BG div around

    $('a.wrapButton:not(.wrappedButton)').addClass('wrappedButton').wrap('<div class="buttonRight"><div class="button"></div></div>');
    //$('a.wrapButton').wrap('<div class="buttonRight"><div class="button"></div></div>');

// controls login box in top nav

    $('#LoginButton').toggle(function() {
        $("#LoginBox").slideDown("normal");
    }, function() {
        $("#LoginBox").slideUp("normal");
    });

// controls my account box in top nav (logged in)

    $('#AccountButton').toggle(function() {
        $("#AccountBox").slideDown("normal");
        $("#Login").addClass("noLoginBG");
    }, function() {
        $("#AccountBox").slideUp("normal");
        $("#Login").removeClass("noLoginBG");
    });

// on summary page, shows export options in widget

$('#ToggleExport').click(function() {
  $('.exportLeads').slideToggle('normal', function() {
  });
});

// adds arrow/blue color when a page is active in the promotoin nav

$('#PromotionNav a').click(function() {
    $("#PromotionNav a").removeClass("selected");
    $(this).addClass("selected");
});

// on summary page, collapses quick stats of current promotion:

$('#ToggleCurrentPromotion').click(function(e) {
    e.preventDefault();
    if ($(this).is(".toggleCurrentPromotionBG")) {
        $("#PromotionDetailed").slideDown("normal");
        $("#ToggleCurrentPromotion").text('Show Less');
        $("#ToggleCurrentPromotion").removeClass("toggleCurrentPromotionBG");
    } else {
        $("#PromotionDetailed").slideUp("normal");
        $("#ToggleCurrentPromotion").text('Show More');
        $("#ToggleCurrentPromotion").addClass("toggleCurrentPromotionBG");
    }
    return false;
});

// button hovers


    $("#BtnSharePromote").hover(
      function () {
    $(this).attr("src", "/images/btn-share-promote-hover.png");
      },
      function () {
    $(this).attr("src", "/images/btn-share-promote.png");
      });

    $(".btnCreatePromotion").hover(
      function () {
    $(this).attr("src", "/images/btn-create-promotion-hover.png");
      },
      function () {
    $(this).attr("src", "/images/btn-create-promotion.png");
      });


    $("input[type=image][name=do_save]").hover(
        function() {
            $(this).attr("src", "/images/button-save-over.png");
        }, function() {
            $(this).attr("src", "/images/button-save.png");
        }
    );

    $("input[type=image][name=do_next]").hover(
            function() {
                $(this).attr("src", "/images/button-save-continue-over.png");
            }, function() {
                $(this).attr("src", "/images/button-save-continue.png");
            }
        );


// end document ready
});




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

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

function eraseCookie(name) {
    createCookie(name, "", -1);
}

