// JavaScript Document

$(document).ready(function () {

    /* -----------------------------------------
    Homepage page, fade in Apply now steps 
    ----------------------------------------------*/

    var count = 1;

    $("img#stepRed" + count).fadeIn(1000, function () { time = setInterval(fademeIn, 2000); });

    function fademeIn() {
        if (count > 3) { count = 0; }
        $("img#stepRed" + count).fadeOut(1000);
        count++;
        $("img#stepRed" + count).fadeIn(1000);
    }

    /* -----------------------------------------
    Form page, blue icon
    ----------------------------------------------*/
    $("a.helpIcon").removeAttr("href");
    $("a.helpIcon").toggle(
        function () {
            var helpInfo = $(this).next();
            helpInfo.css("left", ($(this).position().left + $(this).width() + 30) + 'px');
            helpInfo.fadeIn(1000);
        },
        function () {
            var helpInfo = $(this).next();
            helpInfo.fadeOut(1000);
        }
    );

    /* --------------------------------
    Retailers page, fade in logos 
    -------------------------------------*/


    var counter = -1;

    $("div.contentRetailers img").css({ display: "none" });

    count = setInterval(fading, 100);

    function fading() {
        counter++;
        $("div.greyBoxRetailers img").eq(counter).fadeIn(2000);
        if (counter > 25) {
            clearInterval(count);
        }
    }

    /* --------------------------------
    FAQs page, toggle questions
    -------------------------------------*/

    $("ol#faqList li ul").css({ display: "none" });
    $("ol#faqList li ul li ul").css({ display: "block" });

    $("ol#faqList li a.faqLink").click(function () {
        // SiteCatalyst click tracking
        //var s = s_gi(s_account);
        //s.linkTrackVars = "prop18";
        //s.prop18 = $(this).text();
        //s.tl(this, 'o', 'FAQ Question');
        // animation
        $(this).next().toggle("slow");
        $("ol#faqList li a.faqLink").not(this).next().slideUp("slow")
        return false;
    });

    /*----------------------------------
    lOAN cALCULATOR
    ------------------------------------*/
    if ($('div.sliderControl').length > 0) changeLoanType();
    $('#middleCalc .hide select').customDropdown({ width: 198 });
    $('.SliderFormSmall #inputHowMuch').customDropdown({ prepend: '&euro;' });
    $('.SliderFormSmall #inputHowLong').customDropdown({ append: ' wks' });
    //$('.SliderFormSmall input[type="radio"]').customRadio();

    /* --------------------------------
    homepage visaBanner swap
    -------------------------------------*/


    $("div.banner-2, div.banner-3").css({ display: "none" });
    bannerFade = setInterval(fadeBanners, 10000);

    var visaCounter = 1;

    function fadeBanners() {
        $("div.banner-" + visaCounter).fadeOut(1000, function () {
            visaCounter++;
            $("div.banner-" + visaCounter).fadeIn(1000);
        });

        if (visaCounter >= 3) {
            visaCounter = 0;
        }
    }

    /* --------------------------------
    OnClick tracking 
    -------------------------------------*/
    $("a[href='/Global/Prov_budget_PDF.pdf']").click(function () {
        // SiteCatalyst click tracking
        s.prop20 = 'budgetPlannerPDF';
        s.tl(this, 'o', document.title);
    });

    $("a[href='/PageFiles/102/PDF/Retailers%20across%20the%20UK.pdf']").click(function () {
        // SiteCatalyst click tracking
        s.prop24 = 'retailersPDF';
        s.tl(this, 'o', document.title);
    });

    $("ctl00_MainContent_smallAppForm_btnSubmit").click(function () {
        s.prop25 = 'quickApp Submission';
        s.formList = "quickApply - " + document.title;
        s.tl(this, 'o', document.title);
    });

    $("a[href='/Documents/AffiliateInformationGuide%203_3.pdf']").click(function () {
        s.prop27 = 'affiliatePDF';
        s.tl(this, 'o', document.title);
    });


    $("#ctl00_MainContent_smallAppForm_btnSubmit").click(function () {
        // s.prop25 = 'quickApply Clicked';
        s.tl(this, 'o', document.title);
    });


    if ($("#ctl00_MainContent_B_SAVE_root")) {
        $("#ctl00_MainContent_B_SAVE_root").click(
            function () {
                var cForms = $('.contentForm');
                for (var i = 0; i < cForms.length; i++) {
                    var xy = findXY(cForms[i]);
                    var fader = document.createElement('div');
                    fader.className = 'fader';
                    fader.style.left = xy[0] + 'px';
                    fader.style.top = xy[1] + 'px';
                    fader.style.width = cForms[i].offsetWidth + 'px';
                    fader.style.height = cForms[i].offsetHeight + 'px';
                    var loading = document.createElement('img');
                    loading.className = 'loading';
                    loading.src = "/Resources/images/Loading.gif";
                    loading.style.top = parseInt((cForms[i].offsetHeight / 2) - 150 + xy[1]) + 'px';
                    loading.style.left = parseInt((cForms[i].offsetWidth / 2) - 150 + xy[0]) + 'px';
                    $(fader).appendTo(document.body);
                    $(loading).appendTo(document.body);
                }
                $('select').css("visibility", "hidden");
            }
        );
    }

    /****** Bookmark script *******/
    if (window.opera) $("a.bookmark").attr("rel", "sidebar");

    $("a.bookmark").click(function (event) {
        event.preventDefault();
        var url = this.href;
        var title = this.title;
        if (window.sidebar) window.sidebar.addPanel(title, url, "");
        else if (window.external) window.external.AddFavorite(url, title);
        else if (window.opera) return false;
        else alert('Unfortunately, this browser does not support the requested action, please bookmark this page manually.');
    });

    /*******  recommend a friend *******/

    // big target thing
    $('#mainContent.raf .midPods .rightPod').css('cursor', 'pointer').click(function () {
        if ($(this).find('a').attr('target') == '_blank')
            window.open($(this).find('a').attr('href'));
        else
            window.location = $(this).find('a').attr('href');
    });

    // cloud animation
    var theClouds = function () {
        var container = $('.topImage');
        container.addClass('js');
        var women = $('<div class="women"></div>').appendTo(container);
        var clouds1 = $('<div class="clouds1"></div>').appendTo(container);
        var clouds2 = $('<div class="clouds2"></div>').appendTo(container);
        animateClouds = function (theCloud, startPos, theSpeed) {
            theCloud.animate({ 'left': '+=800' }, theSpeed, 'linear', function () { $(this).css('left', '-' + startPos + 'px'); animateClouds(theCloud, startPos, theSpeed); });
        }
        animateClouds(clouds1, 150, 60000);
        animateClouds(clouds2, 300, 70000);
    }

    if ($.browser.msie && $.browser.version <= "6.0") {
        return;
    } else {
        theClouds();
    }
});

/***************************
Experian form checker
****************************/
function checkExperianForm(theLink){
    var Errors = "Sorry there were errors: \n\n"
    var forename = document.getElementById('preForename').value;
    var surname = document.getElementById('preSurname').value;
    var email = document.getElementById('preEmail').value
    if(forename =='')
        Errors = Errors +  "Please enter your first name \n";
    if(surname =='')
        Errors = Errors + "Please enter your last name \n";
    if(email =='')
        Errors = Errors +  "Please enter your Email address \n";
    else if(valEmail(document.getElementById('preEmail').value)==false)
        Errors = Errors + "Please enter a valid Email Address"

    if(Errors != "Sorry there were errors: \n\n"){
        alert(Errors);
        return false;
    }
    else theLink.href = theLink.href+'&preForename='+forename+'&preSurname='+surname+'&preEmail='+email;
}
function valEmail(str){ return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(str)) }


/***********************
Survey overlay onload and popup on unload
***********************/
var unloadwindow = null;
var unloadWindowName = 'surveyUnloadWindow';

//eraseCookie('survey_cookie');
function surveyOverlay() {
    var survey_cookie = readCookie('survey_cookie');
    if (survey_cookie > 0) return;
    $('<div id="surveyOverlayBack"></div>').appendTo($('body')).css({height:$(document).height() + 'px'});
    var surveyOverlay = $('<div id="surveyOverlay"><div><a id="survey_no" href="#">No</a><a id="survey_yes" href="#">Yes</a></div></div>').appendTo($('body'));
    surveyOverlay.find('#survey_no').click(function () {
        createCookie('survey_cookie', '1', '31');
        $('#surveyOverlayBack, #surveyOverlay').fadeOut('fast');
        pageTracker._trackEvent('Survey', 'OptIn', 'No');
        s.prop28 = 'No';
    });
    surveyOverlay.find('#survey_yes').click(function () {
        createCookie('survey_cookie', '2', '31');
        $('#surveyOverlayBack, #surveyOverlay').fadeOut('fast');
        unloadwindow = displayPopUnder('/survey_holder.aspx?url=' + survey_url, 200, 200);
        pageTracker._trackEvent('Survey', 'OptIn', 'Yes');
        s.prop28 = 'Yes';
    });
}

$(function () {
    var survey_cookie = readCookie('survey_cookie');
    $('a').not('#survey_yes').each(function (i, e) {
        var link = $(this);
        var href = link.attr('href');
        if (null == href) return;
        if (href.indexOf('ttp:') == -1 || (href.indexOf('providentpersonalcredit.ie') < 0 && href.indexOf('localhost') < 0 && href.indexOf('staging-server.co.uk') < 0)) {
            link.click(function () { leave_site = false; });
        }
    });

    $('input[type="submit"], input[type="button"]').click(function () { leave_site = false; });

    $('a').click(function () { showSiteExit = false; });
});

$(window).unload(function () {
    var survey_cookie = readCookie('survey_cookie');
    if (leave_site && survey_url.length > 0 && survey_cookie == 2) {
        createCookie('survey_cookie', '3', '31');
        // re-gain the handle to the window
        unloadwindow = displayPopUnder(survey_url, 1024, 768);
        // you cannot move or resize a window that has content from a different domain.
        unloadwindow.moveTo(0, 0);
        unloadwindow.resizeTo(1024, 768);
        unloadwindow.focus();
    }

    if (showSiteExit && exitId > 0)
        siteExitWin = window.open('/siteexit.aspx?exitId=' + exitId, 'siteExitWin', 'width=700,height=400,status=1,toolbar=1');
});

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    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); }


/***************************
Slider control
****************************/

function sliderControl(controlArea,inExisting) {

    this.existing = inExisting;
    this.sliderArea = controlArea;
    this.sliderArea.innerHTML = "";
    this.startX = null;
    this.sliderStartX = null;

    this.rel = this.sliderArea.getAttribute('rel').split('#');
    this.name = this.rel[0];

    this.minusButton = document.createElement('a');
    this.minusButton.onclick = function() { return false; }
    this.minusButton.className = 'minus';
    this.minusButton.href = '#';
    this.minusButton.onmousedown = createMethodReference(this, this.incrementSlider);

    this.knob = document.createElement('div');
    this.knob.className = 'sliderNob';
    this.knob.onmousedown = createMethodReference(this, this.slideSlider);

    this.slider = document.createElement('div');
    this.slider.className = 'sliderBack';
    this.slider.appendChild(this.knob);
    this.slider.onmousedown = createMethodReference(this, this.jumpSlider);

    this.sliderForeground = document.createElement('div');
    this.sliderForeground.className = 'sliderForeground';

    this.sliderBackground = document.createElement('div');
    this.sliderBackground.className = 'sliderBackground';
    this.sliderBackground.appendChild(this.sliderForeground);
    this.sliderBackground.appendChild(this.slider);

    this.plusButton = document.createElement('a');
    this.plusButton.onclick = function() { return false; }
    this.plusButton.className = 'plus';
    this.plusButton.href = '#';
    this.plusButton.onmousedown = createMethodReference(this, this.incrementSlider);

    this.sliderArea.appendChild(this.minusButton);
    this.sliderArea.appendChild(this.sliderBackground);
    this.sliderArea.appendChild(this.plusButton);

    // Real limits on the slider //
    this.limitHigh = parseInt(this.slider.offsetWidth - this.knob.offsetWidth - 4);
    this.limitLow = 4;
    this.sliderWidth = this.limitHigh - this.limitLow;

    this.newLeft = 0;

    // Imposed limits //
    this.min = (this.rel[1]) ? parseInt(this.rel[1]) : 0;
    this.max = (this.rel[2]) ? parseInt(this.rel[2]) : 100;
    this.range = (this.max == this.min) ? 1 : this.max - this.min;
    this.returnedOffset = (this.rel[3]) ? parseInt(this.rel[3]) : 0;
    this.increment = (this.rel[4]) ? this.rel[4] : 10;

    //populate slider
    this.inputBox = document.getElementById('input' + this.rel[0]);
    this.inputBox.innerHTML = "";

    this.inputBox.onkeyup = createMethodReference(this, this.setTo);
    this.inputBox.onchange = createMethodReference(this, this.setTo);
    this.inputBox.onblur = createMethodReference(this, this.setToLimit);
    
    // defined increment
    if (this.increment.toString().indexOf(",") > -1) {
        var increments = this.increment.toString().split(",");
        for (var i = 0, len = increments.length; i < len; i++) {
            var newOption = document.createElement('option');
            newOption.value = newOption.innerHTML = increments[i];
            this.inputBox.appendChild(newOption);
        }
    }
    else {// standard increment   
        for (var i = this.min; i <= this.max; i = i + parseInt(this.increment)) {
            var newOption = document.createElement('option');
            newOption.value = newOption.innerHTML = i;
            this.inputBox.appendChild(newOption);
        }
    }
    
    // Initialise the sliders to correct position from the input box
    this.setTo();
}

// (Az) Tracking
$(document).ready(function () {
    // (Az) Tracking - Apply Now Button, Loan Calculator
    if ($('div.SliderFormSmall').find('a.continue').length > 0) {
        $('div.SliderFormSmall').find('a.continue').click(function () {
            TrackToolUsage('LoanCalculator', true, 'event3');
        });
    }

    // (Az) Tracking - Loan Type Changed, Loan Calculator
    if ($('#loanOption').length > 0) {
        $('#loanOption').change(function () {
            TrackToolUsage('LoanCalculator', false, 'event3');
        });
    }
});

sliderControl.prototype.incrementSlider = function (event) {
    TrackToolUsage('LoanCalculator', false, 'event3');

    var event = (event == null) ? window.event : event;
    var target = event.target != null ? event.target : event.srcElement;

    for (var c = 0, vals = [], currentVal = 0, len = this.inputBox.length; c < len; c++) {
        vals.push(this.inputBox[c]);
        if (this.inputBox.value == this.inputBox[c].value) currentVal = vals.length - 1;
    }
    if (target.className == 'plus' && currentVal < vals.length - 1) currentVal++;
    if (target.className == 'minus' && currentVal > 0) currentVal--;

    this.inputBox[currentVal].selected = true;
    this.setTo();

    if ($(this.inputBox).prev().attr('class') == 'sliderDropdown') {
        if (this.name == 'HowMuch') $(this.inputBox).prev().find('dt span').html('&euro;' + $(this.inputBox).val());
        else $(this.inputBox).prev().find('dt span').html($(this.inputBox).val() + ' wks');
    }
}

sliderControl.prototype.jumpSlider = function (event) {
    TrackToolUsage('LoanCalculator', false, 'event3');

    var event = (event == null) ? window.event : event;

    this.startX = findX(this.slider);
    this.newLeft = event.clientX + findScrollLeft() - this.startX - (this.knob.offsetWidth / 2) + this.limitLow;

    this.setKnob();
    this.setInputBox();
    this.updateResult();
}

sliderControl.prototype.slideSlider = function (event) {
    TrackToolUsage('LoanCalculator', false, 'event3');

    var event = (event == null) ? window.event : event;

    this.sliderStartX = this.knob.offsetLeft - (event.clientX + findScrollLeft());
    document.onmousemove = createMethodReference(this, this.catchMouseMove);
    document.onmouseup = createMethodReference(this, this.clearMouseMove);

    if (event.preventDefault) event.preventDefault();
    else {
        document.onselectstart = function() { return false; };
        event.cancelBubble = true;
        return false;
    }
}

sliderControl.prototype.catchMouseMove = function(event) {
    var event = (event == null) ? window.event : event;
    var amountMoved = event.clientX + findScrollLeft();

    // new slider position is the position the slider started plus the amount the mouse has moved since the button was held down
    this.newLeft = this.sliderStartX + amountMoved;

    this.setKnob();
    this.setInputBox();
    // Only update results at the bottom on moving the weeks slider
    if (this.name == "HowLong") this.updateResult();
}

sliderControl.prototype.clearMouseMove = function(event) {
    if (this.name == "HowMuch") this.updateResult();

    document.onmousemove = null;
    document.onmouseup = null;
}

sliderControl.prototype.updateResult = function () {
    var loanAllowed = 0, allowedValues = [], currentValues = [], howMuch = parseInt(document.getElementById("inputHowMuch").value), howLong = parseInt(document.getElementById("inputHowLong").value);

    if (howMuch > -1 && howLong > -1) {

        var loanOption = $('select.activeLoan').val();

        if (loanOption == 0) x_loan = lo_loan;
        else if (loanOption == 1) x_loan = lo_voucher;
        else if (loanOption == 2) x_loan = lo_card;
        else if (loanOption == 3) x_loan = lo_high_street;

        for (a = 0, lenx = x_loan.length; a <= lenx - 1; a++) {
            if (x_loan[a][2] == this.existing || x_loan[a][2] == 2) {
                for (b = 3, lenxa = x_loan[a].length; b <= lenxa + 1; b++) {
                    if (parseInt(x_loan[a][b]) == howMuch && x_loan[a][b][2] != "x") {
                        allowedValues.push(parseInt(x_loan[a][0]));
                        if (parseInt(x_loan[a][0]) == howLong) {
                            if (document.getElementById("repayInfo").innerHTML.length < 5) document.getElementById("repayInfo").innerHTML = '<p class="repayLeft">Borrowing &euro;<span id="resultAmount">0</span> at <span id="resultAPR">0</span>&#37; <span class="apr">APR</span>* =</p><p class="repayRight red">Weekly repayment of &euro;<span id="resultWeekly">0</span><br />Total to repay &euro;<span id="resultPayback">0</span></p>';
                            document.getElementById('resultAPR').innerHTML = x_loan[a][1];
                            document.getElementById('resultWeekly').innerHTML = x_loan[a][b][3];
                            document.getElementById('resultPayback').innerHTML = x_loan[a][b][2];
                            document.getElementById('resultAmount').innerHTML = howMuch;
                            loanAllowed = 1;
                        }
                    }
                }
            }
        }

        if (this.name == "HowMuch") {
            var howLongSelect = document.getElementById('inputHowLong');
            var currentOption = 0;
            while (howLongSelect[currentOption]) {
                currentValues.push(parseInt(howLongSelect[currentOption].value));
                currentOption++;
            }
        }

        if (this.name == "HowMuch" && (loanAllowed == 0 || currentValues.toString() != allowedValues.toString())) {

            var inputTemp = document.getElementById('inputHowLong');
            var oldVal = inputTemp.value;
            var durControl = document.getElementById("durationControl");
            durControl.innerHTML = "";

            if (allowedValues.length == 1)
                durControl.setAttribute("rel", "HowLong#" + allowedValues[0] + "#" + allowedValues[allowedValues.length - 1] + "#1#");
            else
                durControl.setAttribute("rel", "HowLong#" + allowedValues[0] + "#" + allowedValues[allowedValues.length - 1] + "##" + allowedValues.join(","));

            var newControl = new sliderControl(durControl, this.existing);

            // Find input box value closest to term
            if (parseInt(inputTemp[0].value) >= oldVal) inputTemp[0].selected = true;
            else if (parseInt(inputTemp[inputTemp.length - 1].value) <= oldVal) inputTemp[inputTemp.length - 1].selected = true;
            else inputTemp.value = oldVal;
            newControl.setTo();

            if ($(newControl.inputBox).prev().attr('class') == 'sliderDropdown') { $(newControl.inputBox).customDropdown({ append: ' wks' }); }
        }
    }
}

sliderControl.prototype.setTo = function (inValue) {
    var newValue = (inValue > -1) ? inValue : parseInt(this.inputBox.value);
    if (Math.abs(newValue) > -1) {
        this.newLeft = Math.floor(((newValue - this.min) / this.range) * this.sliderWidth) + this.limitLow - (this.knob.offsetWidth / 2);
        this.setKnob();
        this.updateResult();
    }
}

sliderControl.prototype.setKnob = function(inValue) {
    if (inValue) this.newLeft = inValue;
    
    this.newLeft = (this.newLeft > this.limitHigh) ? this.limitHigh : this.newLeft;
    this.newLeft = (this.newLeft < this.limitLow) ? this.limitLow : this.newLeft;
    this.sliderForeground.style.width = parseInt(this.newLeft + (this.knob.offsetWidth / 2)) + 'px';
    this.knob.style.left = this.newLeft + 'px';
}

sliderControl.prototype.setInputBox = function () {
    var newValue = 0;
    if (this.newLeft <= this.limitLow) newValue = this.min;
    else if (this.newLeft >= this.limitHigh) newValue = this.max;
    else newValue = Math.ceil((this.newLeft / this.sliderWidth) * this.range) + this.min;

    var currentOption = 1;
    var foundVar = -1;

    // Cycle through the childnodes finding the closest option to the value from the slider.
    while (foundVar == -1 && this.inputBox[currentOption]) {
        if (parseInt(this.inputBox[currentOption].value) >= newValue) {
            if (!this.inputBox[currentOption - 1]) foundVar = parseInt(this.inputBox[currentOption].value);
            else if (newValue - parseInt(this.inputBox[currentOption - 1].value) < parseInt(this.inputBox[currentOption].value) - newValue) foundVar = parseInt(this.inputBox[currentOption - 1].value);
            else foundVar = parseInt(this.inputBox[currentOption].value);
        }
        currentOption++;
    }
    if (!this.inputBox[currentOption] && foundVar == -1) this.inputBox[currentOption - 1].selected = true;
    else this.inputBox.value = foundVar;

    if (foundVar > -1 && $(this.inputBox).prev().attr('class') == 'sliderDropdown') {
        if (this.name == "HowMuch") $(this.inputBox).prev().find('dt span').html('&euro;' + foundVar);
        else $(this.inputBox).prev().find('dt span').html(foundVar+' wks');
    }
}

/***********************
General functions
************************/

function findX(obj) {
    var curX = 0;
    if (obj.offsetParent) {
        do { curX += obj.offsetLeft; } while (obj = obj.offsetParent);
    }
    return curX;
}

function findXY(obj){
    var curX = curY = 0;
    if (obj.offsetParent) {
        do {
            curX += obj.offsetLeft;
            curY += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curX,curY];
}

function findScrollLeft() {
    var scrollLeft = document.body.scrollLeft;
    if (scrollLeft == 0) {
        if (window.pageXOffset)
            scrollLeft = window.pageXOffset;
        else
            scrollLeft = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
    }
    return scrollLeft;
}

function createMethodReference(object, method) {
    if (!(method instanceof Function)) method = object[method];
    if (method) return function() { method.apply(object, arguments); };
    else return null;
}

function displayPopUnder(url, width, height) {
    win = window.open(url, unloadWindowName, 'width=' + width + ',height=' + height);
    if (win != null) win.blur();
    window.focus();
    return win;
}


/***********************
    Hampers Bookmark page
    ********************/
    
$(document).ready(function(){
    // add a "rel" attrib if Opera 7+
    if(window.opera) {
        if ($("a.bookmark").attr("rel") != "") { // don't overwrite the rel attrib if already set
            $("a.bookmark").attr("rel", "sidebar");
        }
    }
 
    $("a.bookmark").click(function(event){
        event.preventDefault(); // prevent the anchor tag from sending the user off to the link
        var url = this.href;
        var title = this.title;
 
        if (window.sidebar) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(title, url,"");
        } else if( window.external ) { // IE Favorite
            window.external.AddFavorite( url, title);
        } else if(window.opera) { // Opera 7+
            return false; // do nothing - the rel="sidebar" should do the trick
        } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
             alert('Unfortunately, this browser does not support the requested action,'
             + ' please bookmark this page manually.');
        }
 
    });
});




// PLUGINS


 (function ($) {
     $.fn.customDropdown = function (options) {
         var opts = $.extend({}, $.fn.customDropdown.defaults, options);
         return this.each(function () {

             var selectBox = $(this);

             if (selectBox.prev().attr('class') == 'sliderDropdown') selectBox.prev().remove();

             var selectedHTML = $(this).find('[value="'+$(this).val()+'"]').html();

             var selected = $('<dt class="select'+selectBox.attr('name')+'"><span>' + opts.prepend + selectedHTML + opts.append + '</span></dt>')
                        .css({ width: opts.width + 'px' })
                        .hover(
                            function () { $(this).addClass(opts.selectHoverClass); },
                            function () { $(this).removeClass(opts.selectHoverClass); }
                        );

             var options = $(this).find('option');

             var newSelect = $('<dl class="' + opts.classname + '" rel="' + $(this).attr('id') + '"></dl>')
                        .click(
                            function (e) {
                                var newOptions = $(this).find('ul');
                                var optionsHolder = $(this).find('dd');

                                if (newOptions.is(':visible')){
                                    newOptions.slideUp('fast', function () { optionsHolder.hide(); });
                                    if (selectBox.attr('name') == 'inputHowMuch') $('.selectinputHowlong').show();
                                }
                                else {
                                    optionsHolder.show().css('border', '1px solid #D0D0D0');
                                    var aboveY = e.clientY;
                                    var belowY = $(window).height() - e.clientY;

                                    var maxHeight = (aboveY > belowY) ? aboveY : belowY;
                                    if (maxHeight >= 250) maxHeight = 250;  
                                    optionsHolder.css({ height: 'auto', overflow: 'hidden', width: opts.width });

                                    if (aboveY > belowY) optionsHolder.css({ bottom: opts.selectHeight + 'px', top: 'auto' });
                                    else{
                                        optionsHolder.css({ top: opts.selectHeight + 'px', bottom: 'auto' });
                                        if (selectBox.attr('name') == 'inputHowMuch') $('.selectinputHowlong').hide();
                                    }
                                    newOptions.slideDown('fast', function () { if (optionsHolder.height() > maxHeight) optionsHolder.css({ height: (maxHeight - 20) + 'px', overflowY: 'scroll', overflowX: 'hidden' }); });
                                }
                            }
                        );
             var newList = $('<ul></ul>').hide().css({width: opts.width});
             options.each(function () {
                 var newLi = $('<li rel="'+$(this).val()+'">' + $(this).html() + '</li>')
                            .css({ height: opts.optionHeight + 'px' })
                            .hover(
                                function () { $(this).addClass(opts.optionHoverClass); },
                                function () { $(this).removeClass(opts.optionHoverClass); }
                            )
                            .click(function () {
                                $(this).parent().find('.'+opts.selectedClass).removeClass(opts.selectedClass);
                                var newHtml = $(this).addClass(opts.selectedClass).html();
                                var newVal = $(this).addClass(opts.selectedClass).attr('rel');
                                var dl = $(this).parent().parent().parent();
                                dl.find('dt span').html(opts.prepend + newHtml + opts.append);
                                dl.next().val(newVal).change();
                                // (Az) Tracking - Custom Dropdown Change, Loan Calculator
                                TrackToolUsage('LoanCalculator', false, 'event3');
                            });
                 newList.append(newLi);
             });
             var dd = $('<dd></dd>').append(newList); //.css({top:opts.selectHeight + 'px'});
             newSelect.append(selected).append(dd);
             $(this).css({ display: 'none' }).before(newSelect);
         });
     }
     $.fn.customDropdown.defaults = {
         classname: 'sliderDropdown',
         optionHoverClass: 'hover',
         selectHoverClass: 'hover',
         selectedClass: 'selected',
         selectHeight: 24,
         optionHeight: 25,
         width: 73,
         prepend: '',
         append: ''
     }

     $.fn.customRadio = function (options) {
         var opts = $.extend({}, $.fn.customRadio.defaults, options);
         return this.each(function () {

            var radioButton = $(this);

            radioButton.hide();
            var radioOn = $('<img src="'+opts.imgRadioOn+'" class="'+radioButton.attr('name')+'RadioOn" style="display:none;" />');
            var radioOff = $('<img src="'+opts.imgRadioOff+'" class="'+radioButton.attr('name')+'RadioOff" style="display:none;" />');
            
            radioButton.before(radioOn).after(radioOff);
            
            if (radioButton.is(':checked')) radioOn.show().parent().addClass(opts.labelOnClass);
            else radioOff.show();

            radioOn.click(function(){
                radioOn.hide();
                radioButton.next().show();
                radioButton.removeAttr('checked');
                radioButton.parent().removeClass(opts.labelOnClass);
            });

            radioOff.click(function(){
                $('.'+radioButton.attr('name')+'RadioOn').hide().parent().removeClass(opts.labelOnClass);
                $('.'+radioButton.attr('name')+'RadioOff').show();
                radioOff.hide();
                radioButton.prev().show();
                radioButton.attr('checked','checked');
                radioButton.click();
                radioButton.parent().addClass(opts.labelOnClass);
            });

            radioButton.change(function(){
                if (radioOff.is(':visible')) radioOff.click();
                else radioOn.click();
            });

         });
     }
     $.fn.customRadio.defaults = {
         classname: 'sliderRadio',
         imgRadioOn: '/Resources/images/homepage/sliderRadioOn.gif',
         imgRadioOff: '/Resources/images/homepage/sliderRadioOff.gif',
         selectedClass: 'selected',
         labelOnClass: 'labelOn',
         dimensions: [12,12]
     }
 })(jQuery);



 /*************** love 2 shop offers **************/

 function renderPagination(){
    var offers = $('.leftPod, .rightPod');
    if (offers.length < 6) return;

    $('.paginationArea').css({height: offers.eq(0).height() * 3});

    for (var i = 0, len = offers.length; i < len; i++) {
        if ((i + 1) % 2 == 0)
            offers.eq(i).css({ position: 'absolute', top: Math.floor((i % 6) / 2) * (offers.eq(i).height() + 1), right: 0 });
        else
            offers.eq(i).css({ position: 'absolute', top: Math.floor((i % 6) / 2) * (offers.eq(i).height() + 1), left: 0 });
    }

    var pages = []
    var pagination = $('<div class="pagination"><span class="next">Next</span><ul></ul><span class="prev">Previous</span></div>');

    for(var i = 0, len = offers.length; i < len; i = i + 6){
        var p = (i + 6 < len) ? i + 6 : len;
        var currentPage = pages.length;

        pages.push(offers.slice(i,p));

        var pageLink = $('<li>' + (currentPage + 1) + '</li>').appendTo(pagination.find('ul'));

        if (i > 0) offers.slice(i, p).hide();
        else pageLink.attr('rel', 'selected').css({ backgroundPosition: '0 -22px' });
    }

    var botPage = pagination.clone();

    botPage.find('li').add(pagination.find('li'))
            .click(function () {
                var pageIndex = $(this).html();
                if ($(this).attr('rel') == 'selected') return;

                $('.pagination li').attr('rel', '').css({ backgroundPosition: '0 0' });
                $('.pagination').each(
                    function () {
                        $(this).find('li').eq(pageIndex - 1).attr('rel', 'selected').css({ backgroundPosition: '0 -22px' });
                    }
                );
                offers.slideUp('slow');
                pages[pageIndex - 1].slideDown('slow');
            });

    $('.paginationArea').before(pagination).after(botPage);

    $('.pagination .prev').click(
        function () { $('.pagination li[rel="selected"]').prev('li').trigger('click'); }
    );
    $('.pagination .next').click(
        function () { $('.pagination li[rel="selected"]').next('li').trigger('click'); }
    );

 }
 
 function dealOverlay(){
    $('.leftPod a, .rightPod a').click(function () { return false; });
    $('.leftPod, .rightPod')
        .css({ cursor: 'pointer' })
        .hover(
            function () { $(this).css({ background: '#f1f1f1' }).find('a').css({ textDecoration: 'underline' }); },
            function () { $(this).css({ background: '#fff' }).find('a').css({ textDecoration: 'none' }); })
        .click(
            function () {
                var postVars = { deal: $(this).find('a').attr('rel') };

                $('#offerText .loading').show();
                $('#offersOverlay')
                    .css({ opacity: 0.1, display: 'block' })
                    .animate({ opacity: 0.5, height: $('form').height() }, 500, 'swing',
                        function () {
                            var offerPosition = $(window).scrollTop() + 100;
                            $('#offerText').css({ top: offerPosition }).fadeIn('fast');
                            $('#offerText .closeLink').click(
                                function () {
                                    $('#offersOverlay').hide().css({ height: 0 });
                                    $('#offerText, .offerTitle, .offerImage, .offerDetails, .offersApplyNow').hide();
                                }
                            );
                        }
                    )
                    .click(
                        function () {
                            $(this).hide().css({ height: 0 });
                            $('#offerText, .offerTitle, .offerImage, .offerDetails, .offersApplyNow').hide();
                        }
                    );

                $.post('/Resources/PageTemplates/love2shop_deal.ashx', postVars,
                    function (data) {
                        var json = eval('(' + data + ')');
                        $('#offerText .loading').hide();
                        $('#offerText .offerImage').show().attr('src', json.image);
                        $('#offerText .offerTitle').show().html(json.title);
                        $('#offerText .offerDetails').show().html(json.details);
                        $('#offerText .offersApplyNow').show();
                    }, 'text');
            }
        )
        .find('a').click(function () {
            $(this).parent().click();
            return false;
        });
}

var slideShowInterval = null

function dealSlideShow(){
    var slides = $('div.slide');
    slides.eq(0).addClass('active').nextAll().hide();
    for (var i = 0, len = slides.length; i < len; i++) {
        var link = $('<a href="#" rel="'+i+'"></a>').html(i + 1);
        $('.slideshow .controls ul').append($('<li />').append(link));
    }
    $('.slideshow .controls ul a')
        .click(function () {
            clearInterval(slideShowInterval);
            $('div.slide.active').removeClass('active').fadeOut('fast');
            $('div.slide').eq($(this).attr('rel')).addClass('active').fadeIn('fast');
            $('.controls a.selected').removeClass('selected');
            $(this).addClass('selected');
            return false;
        })
        .eq(0).addClass('selected');

        if ($('div.slide').length > 1) {
            slideShowInterval = setInterval(function () {
                var next = null;
                var slides = $('.frameHolder').children();
                for (var i = 0, len = slides.length; i < len; i++) {
                    if (slides.eq(i).hasClass('active')) {
                        next = (i < len - 1) ? i + 1 : 0;
                    }
                }
                $('div.slide.active').removeClass('active').fadeOut('fast');
                slides.eq(next).addClass('active').fadeIn('fast');
                $('.slideshow .controls ul a.selected').removeClass('selected');
                $('.slideshow .controls ul a[rel="' + next + '"]').addClass('selected');
            }, 8000);
        }

}

/*** Current Customers ***/
$(function () {
    if ($('#bannerHolder').length > 0) {
        var banners = $('#bannerHolder>div');
        var bVis = banners.filter(':visible');
        if (bVis.length == 0) banners.eq(0).show();
        var currentBanner = 0;
        setInterval(
            function () {
                currentBanner++;
                if (currentBanner >= banners.length) currentBanner = 0;

                banners.filter(':visible').fadeOut('fast');
                banners.eq(currentBanner).fadeIn('fast');
            }
        , 5000);
    }
});

/****** Mobiles *****/

var mobiles = [];

$(function () {

    $('#mobileContent .bullets ul .tooltip').each(
        function () {
            $(this).hover(
                function () {
                    var tt = $(this).css({ cursor: 'pointer' }).find('.tts');
                    tt.css({ display: 'block' });
                    tt.css({ top: -tt.height() - 3, left: -(tt.width() / 2) });

                    $(this).find('.arrow').show();
                },
                function () {
                    $(this).find('.tts').fadeOut('fast');
                    $(this).find('.arrow').fadeOut('fast');
                }
            );
        }
    );

    $('#mobileImages .thumbs li')
        .css({ display: 'block' })
        .click(
            function () {
                $('#mobileImages .thumbs li').css({ borderColor: '#d0d0d0' });
                $(this).css({ borderColor: '#e67824' });
                $('#mobileImages>img').attr('src', $(this).find('img').attr('src'));
            }
        )
        .filter(':first').css({ borderColor: '#e67824' });

    $('.phonesList > .imageHolder').each(
        function () {
            var img = $(this).find('img');

            img.attr('rel', img.position().left + '#' + img.height())
                .css({ position: 'absolute', left: img.position().left, top: 0 })
                .mouseover(function () {
                    var curImg = $(this);
                    curImg.stop(true, true).css({ height: 'auto', zIndex: '1000000', border: '3px solid #b7b7b7' });
                    var newLeft = ((curImg.parent().parent().width() - curImg.width()) / 2);
                    var newTop = (curImg.parent().parent().height() - curImg.height()) / 2;
                    curImg.css({ left: newLeft + 'px', top: newTop + 'px' });
                })
                .mouseout(function () {
                    var curImg = $(this);
                    curImg.animate({ height: parseInt(curImg.attr('rel').split('#')[1]), left: parseInt(curImg.attr('rel').split('#')[0]), top: 0, borderWidth: 0 }, 'fast', 'swing', function () { $(this).css({ zIndex: '100', display: '' }); });
                });

        }
    );


    $('.phoneListHeader > select').customDropdown({ width: 196, selectHeight: 34, optionHeight: 20, classname: 'phoneDropdown' });

    $('.PhoneOrder').change(function () {

        if ($.browser.msie && $.browser.version <= "6.0") {
            var queryPos = (window.location.href.indexOf('?') > 0) ? window.location.href.indexOf('?') : window.location.href.length;
            window.location = window.location.href.substr(0, queryPos) + '?sort=' + parseInt($(this).val()) + '#mobiles';
            return;
        }

        switch (parseInt($(this).val())) {
            case 0:
                mobiles.sort(sortByPriceDesc);
                break;
            case 1:
                mobiles.sort(sortByPriceAsc);
                break;
            case 2:
                mobiles.sort(sortByPopularity);
                break;
        }

        var oldBig = $('.phonesList .bigPod');
        if (oldBig.length > 0) {
            oldBig.removeClass('bigPod').addClass('phonePod');
            oldBig.find('img')
                .css({ position: '', left: '', height: '' })
                .attr('rel', Math.round(oldBig.find('img').position().left) + '#' + oldBig.find('img').height())
                .css({ position: 'absolute', left: oldBig.find('img').position().left, top: 0 })
            oldBig.find('.imageHolder').css({ height: oldBig.find('img').height() });
        }

        for (var i = 0, len = mobiles.length; i < len; i++) {
            $('.phonesList div[rel="phone' + mobiles[i].id + '"]').appendTo('.phonesList');
        }

        var allPhones = $('.phonesList .phonePod');
        if (allPhones.length % 4 == 1) {
            var newBig = $('.phonesList .phonePod:last');
            newBig.removeClass('phonePod').addClass('bigPod');
            newBig.find('img')
                .css({ position: '', left: '', height: '' })
                .attr('rel', newBig.find('img').position().left + '#' + newBig.find('img').height())
                .css({ position: 'absolute', left: newBig.find('img').position().left, top: 0 });
            newBig.find('.imageHolder').css({ height: newBig.find('img').height() });
        }

    });
});

function sortByPriceAsc(a, b) {
    var x = parseInt(a.price);
    var y = parseInt(b.price);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByPriceDesc(a, b) {
    var x = parseInt(a.price);
    var y = parseInt(b.price);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function sortByPopularity(a, b) {
    var x = parseInt(a.popularity);
    var y = parseInt(b.popularity);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

/****** GENERIC OVERLAY and SITE EXIT *******/

var genericTimeout = null;
var selects = null;
var modalShown = false;

window.onload = function () {
    if (ModalDelay > 0 && (readCookie('ppcTraffic') == null || readCookie('ppcTraffic') == 0)) {
        startModalTimer(ModalDelay);
        $('form')
            .mousemove(function () { if (!modalShown) startModalTimer(ModalDelay); })
            .keypress(function () { if (!modalShown) startModalTimer(ModalDelay); })
            .click(function () { if (!modalShown) startModalTimer(ModalDelay); });
    }

    if (siteExitTimer > -1 && (readCookie('ppcTraffic') == null || readCookie('ppcTraffic') == 0)) setTimeout(function () { showSiteExit = true; }, 1000 * siteExitTimer);
}

function startModalTimer(delay) {
    if ($('#genericOverlay').is(':visible')) return;
    else {
        clearTimeout(genericTimeout);
        genericTimeout = setTimeout(function () { showModal(); }, delay);
    }
}

function showModal() {
    modalShown = true;
    if ($.browser.msie && $.browser.version <= "6.0") selects = $('select:visible').css({ visibility: 'hidden' });
    $('#genericOverlay')
        .css({ opacity: 0.1, display: 'block' })
        .animate({ opacity: 0.5, height: $('form').height() }, 500, 'swing',
            function () {
                var modalPosition = $(window).scrollTop() + 100;
                $('#genericModal').css({ top: modalPosition }).fadeIn('fast');
                $('#genericModal .genericClose').click(function () { closeModal(); });
            }
        )
        .click( function () { closeModal(); } );        
        
}

function closeModal() {
    if (selects) selects.css({ visibility: 'visible' });
    $('#genericOverlay').animate({ opacity: 0.1, height: 0 }, 500, 'swing', function () { $(this).css({ display: 'none' }); });
    $('#genericModal').hide();
}
