// JavaScript Document

$(document).ready(function() {

    /* -----------------------------------------
    Homepage page, fade in Apply now steps 
    ----------------------------------------------*/

    var image1 = $('<img />').attr({ src: '/Resources/images/stepOneRed.gif', id: 'stepRed1' });
    var image2 = $('<img />').attr({ src: '/Resources/images/stepTwoRed.gif', id: 'stepRed2' });
    var image3 = $('<img />').attr({ src: '/Resources/images/stepThreeRed.gif', id: 'stepRed3' });

    image1.insertAfter('ul.reasonsWhy');
    image2.insertAfter('img#stepRed1');
    image3.insertAfter('img#stepRed2');

    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);

    }

    // this makes no sense. please do not comment it back in without speaking to greg
    //    $("input").focus(function() {
    //        var text = $(this).text();
    //        $(this).val(text);
    //    })

    /* -----------------------------------------
    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;
    });
    /*
    var showFaq = $('a[href$="'+location.pathname+'"]').next();
    if (showFaq){
    showFaq.css("display","block");
    $(window).scrollTop(showFaq.position().top - 20);
    }
    */

    /*----------------------------------
    lOAN cALCULATOR
    ------------------------------------*/
    if ($('div.sliderControl').length > 0) changeLoanType();



    /* --------------------------------
    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.');
    });    
});

/***************************
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)) }



/***************************
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();
}

sliderControl.prototype.incrementSlider = function(event) {
    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();
}

sliderControl.prototype.jumpSlider = function(event) {
    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) {
    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 > 0 && howLong > 0){
        
        if (document.getElementById("loanOption").selectedIndex == 0)      x_loan = lo_loan;
        else if (document.getElementById("loanOption").selectedIndex == 1) x_loan = lo_voucher;
        else if (document.getElementById("loanOption").selectedIndex == 2) x_loan = lo_card;

        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) {
                            document.getElementById("repayInfo").innerHTML = '<p class="repayLeft">Borrowing &pound;<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 &pound;<span id="resultWeekly">0</span><br />Total to repay &pound;<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 = "";
            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();
        }
    }
}

sliderControl.prototype.setTo = function(inValue) {
    var newValue = (inValue) ? inValue : parseInt(this.inputBox.value);
    if (Math.abs(newValue) > 0) {
        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;
}

/***********************
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) {
    var win = window.open(url, '', 'width=' + width + ',height=' + height + ',left=200,top=200');
    if (win != null) win.blur();
    window.focus();
}


/***********************
    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.');
        }
 
    });
});


	
