﻿/*****************************************************
  Function to scroll images on the right hand side
******************************************************/
function DoScrolling(iSpeed)
{
    var oParent = $('#divScroller');
    if(oParent.length<=0) return;
    var oUl = $("ul",oParent);
    var iMax = -1 * (oUl.height() - oParent.height());
    if(!oUl[0].style.marginTop) 
        oUl[0].style.marginTop='0px';
    var iPos = parseInt(oUl[0].style.marginTop) + oUl.position().top;
    if(iPos>(iMax + oUl.position().top))
    {
        window._CurrentScrollTop += 1;
        var oLi = $('li', oUl[0]).eq(window._CurrentScrollTop);
        if (oLi.length>0) 
            iPos -= (oLi.position().top);
        else
        {
            iPos = 0;
            window._CurrentScrollTop = 0;
        }
    }
    else
    {
        iPos = 0;
        window._CurrentScrollTop = 0;
    }

	oUl.animate(
		{ marginTop: iPos}, 
		iSpeed);

    clearTimeout(window._ScrollTimer);
    window._ScrollTimer = setTimeout("DoScrolling(2000)",3000);
}

/*****************************************************
  Function to manually scroll images on the 
  right hand side
******************************************************/
function GetNextScroll()
{
    clearTimeout(window._ScrollTimer);
    DoScrolling(50);
}

/*****************************************************
  Function to handle tab selection
******************************************************/
function DoTabSelect(sTab)
{
    if(window._ScrollTimer)
        clearTimeout(window._ScrollTimer);

    window._NewTabId = sTab;
    
    $('#divWaiter').show();//.slideDown('fast');
    
    //this is to update the stupid IE.
    while($('#divWaiter:visible').length<=0) document.title="Waiting...";

    var sUrl = 'getcontent.aspx?reqtype=tab&key={0}&ref={2}&UID={1}'.format(window._NewTabId, 
                        escape((new Date()).toUTCString()), $('#hdnIntroducerRef').val());
                        
    //in case if this is hidden by the iframe;
    $('#ajaxContent').show();
    $('#ajaxContent').load(sUrl, 
        function() {
            $('#MenuItem' + window._CurrentMenuItem.toString()).removeClass('MenuItemSelected');
            $('#MenuItemText' + window._CurrentMenuItem.toString()).removeClass('MenuItemTextSelected');
            window._CurrentMenuItem = window._NewTabId;
            $('#MenuItem' + window._NewTabId.toString()).addClass('MenuItemSelected');
            $('#MenuItemText' + window._NewTabId.toString()).addClass('MenuItemTextSelected');
            document.title = 'MyClubMyMoney.Com : ' + $('#MenuItemText' + window._NewTabId.toString()).text();
            
            $('#divWaiter').hide();//.slideUp('fast');
            InitControls(this);
            window._ScrollTimer = setTimeout("DoScrolling(2000)",3000);
        });
}

/*****************************************************
        Apply hover effect on tabs
******************************************************/
function ApplyHoverEffect()
{
    $("div.MenuItem").click(function(){
        $("a", this).trigger('click');
    });
    
    $("div.MenuItem").mouseenter(function(){
        $(this).addClass('MenuItemHover');
        $('.MenuItemText',this).addClass('MenuItemTextHover');
    });
    
    $("div.MenuItem").mouseleave(function(){
        $(this).removeClass('MenuItemHover');
        $('.MenuItemText',this).removeClass('MenuItemTextHover');
    });
}

/*****************************************************
  Ajax History call back function
******************************************************/
function AjaxCllback(hash)
{
    if(hash)
        DoTabSelect(hash);
    else if (!bFirstTime) 
        DoTabSelect('home');
    else
        bFirstTime=false;
}

/*****************************************************
  Function to initialise controls after Ajaxified 
  load event
******************************************************/
function InitControls(parent)
{
    $("a[rel='history']", parent).click(function(){
        $.history.load(this.href.replace(/^.*#/, ''));
        return false;
    });
    
    window._CurrentScrollTop = 0;
    
    $('input.Currency').change( function() {
        this.value = this.value.replace(/[£,]/g,'').formatCurrency(2,'£');
    });
    
    $('input.Percentage').change( function() {
        this.value = parseFloat(this.value) + '%' ;
    });
    
    $('input.Integer').change( function() {
        this.value = parseInt(this.value);
    });
    
    
    $("a.popup", parent).click(function(){
        var jThis = $(this); 
        OpenModalDialog(jThis, jThis.text(), jThis.attr('href'));
        return false;
    });
    
    setTimeout("PostloadImages()", 200);
    
    if(document.all) $('div.curvyRedraw').corner();
    
    InitialiseSliders();
    
    //Load from cookie
    getCookie('txtMortCalc_IR');
    getCookie('txtMortCalc_Loan');
    getCookie('txtMortCalc_Term');
    
    getCookie('txtProp_SalePrice');
    getCookie('txtProp_Commission');
    
    UpdateCookies();
   
}

function PostloadImages()
{
    //post loading images
    var postImgs=$("img.postload_src");
    for(var i=0;i<postImgs.length;i++)
    {
        var indimg = $(postImgs[i]);
        indimg.attr("src",indimg.attr("alt"));
        indimg.show();
    }
}

function InitialiseSliders()
{
    var sliders = $('div.slider');
    for(var i=0;i<sliders.length;i++)
    {
        var oSlider = $(sliders[i]);
        var oMin = parseFloat(oSlider.attr('min'));
        var oMax = parseFloat(oSlider.attr('max'));
        var oStep = parseFloat(oSlider.attr('step'));
        
        oSlider.slider({
            slide:function(){
                adjestValue(this.id);
            },
            min:oMin,
            max:oMax,
            step:oStep
        });
    }
}

function adjestValue(sliderid)
{
    var sliderCnt = $('#' + sliderid);
    var control = $('#' + sliderCnt.attr('target'));
    var value = sliderCnt.slider('option','value');
    switch(sliderCnt.attr('format'))
    {
        case '%': value+='%'; break;
        case '£': value=value.toString().formatCurrency(2,'£');break;
    }
    control.val(value);
}

/*****************************************************
    Load the Request a Call widget thingy
******************************************************/
function ToggleCallBack()
{
    if($('#divRequest_Call_Back:visible').length<=0)
    {
        if($('#divRequest_Call_Back:empty').length>0)
        {
            var sUrl = 'getcontent.aspx?reqtype=tab&key=reqcallback&ref={0}&UID={1}'.format($('#hdnIntroducerRef').val(),
                                        escape((new Date()).toUTCString()));
            $('#divRequest_Call_Back:empty').load(sUrl, function() {
               $('#divRequest_Call_Back').slideDown('slow');
               $('input.Phone').mask('99999-999999');
            });
        }
        else
            $('#divRequest_Call_Back').slideDown('slow');
    }
    else
        $('#divRequest_Call_Back').slideUp('slow');
}

/*****************************************************
    Submit the Call back form using Ajax
******************************************************/
function DoSubmitCallback()
{
    if($('#txtReqCallBack_Name').val().length<=0)
    {
        alert('Please enter your name');
        $('#txtReqCallBack_Name').focus();
        return;
    }
    
    if($('#txtReqCallBack_ContactNo').val().length<=0)
    {
        alert('Please enter your contact number');
        $('#txtReqCallBack_ContactNo').focus();
        return;
    }
    
    var sUrl = ('RequestCallBack.aspx?ref={0}&ContactName={1}&' +
                'ContactNumber={2}&ContactNotes={3}&key={4}').format(
                $('#hdnIntroducerRef').val(), 
                escape($('#txtReqCallBack_Name').val()),
                escape($('#txtReqCallBack_ContactNo').val()), 
                escape($('#txtReqCallBack_Notes').val()),
                window._CurrentMenuItem);
    $('#divRequest_CallBack_Button').hide();
    $('#divRequest_CallBack_Progress').show();
    $('#divRequest_Call_Back').load(sUrl, function() {
        $('#divRequest_CallBack_Progress').hide();
    });
}

/*****************************************************
    Builds mlcalc Mortgage widget API link
******************************************************/
function UpdateCookies()
{
    if($('#txtMortCalc_IR').length<=0) return;
    
    var intRate = parseFloat($('#txtMortCalc_IR').val().replace('%',''));
    //$("div[target='txtMortCalc_IR']").slider('option', 'value', intRate);
    if(isNaN(intRate)) 
    {
        $('#txtMortCalc_IR').val('4.5%');
        intRate=4.5;
    }
    setCookie("txtMortCalc_IR", 30);
    
    var amount = parseFloat($('#txtMortCalc_Loan').val().replace(/[£,]/g,''));
    //$("div[target='txtMortCalc_Loan']").slider('option', 'value', amount);
    if(isNaN(amount)) 
    {
        $('#txtMortCalc_Loan').val('£200,000.00');
        amount=200000;
    }
    setCookie("txtMortCalc_Loan",  30);
    
    var term = parseInt($('#txtMortCalc_Term').val());
    //$("div[target='txtMortCalc_Term']").slider('option', 'value', term);
    if(isNaN(term)) 
    {
        $('#txtMortCalc_Term').val('25');
        term=25;
    }
    setCookie("txtMortCalc_Term", 30);
}

/*****************************************************
    Opens up a new window with the product 
    processing URL
******************************************************/
function GotoLink(linkId, params, introducerParamName)
{
    params = params?params:'';
    introducerParamName = introducerParamName?introducerParamName:'IntroducerRef';
    var sVars = '{2}={0}&{1}'.format($('#hdnIntroducerRef').val(), params, introducerParamName);
    var sUrl = "getcontent.aspx?reqtype=ext&key={0}&ref={2}&params={1}".format(linkId, escape(sVars),
                            $('#hdnIntroducerRef').val())
    window.open(sUrl);
}

/*****************************************************
    Opens up a new window with the product 
    processing URL
******************************************************/
function GotoExLink(linkUrl)
{
    linkUrl = linkUrl.replace("[$Ref]", $('#hdnIntroducerRef').val());
    window.open(linkUrl);
}

/*****************************************************
    Opens up Ajaxy window with a url
    (These pages can not have script tags)
******************************************************/
function OpenModalDialog(src, title, url)
{
    url=unescape(url);
    if($('#mcmm_dialog_content')[0]._CurrentUrl!=url)
    {
        $('#mcmm_dialog_content')[0]._CurrentUrl=url;
        $('#mcmm_dialog_content').load(url, function() {
            ShowDialog(title,src);
        });
    }
    else
    {
        ShowDialog(title,src);
    }
}

function ShowDialog(title, src)
{   
    var width = parseInt(src.css('width')); 
    var height = parseInt(src.css('height'));

    if(!width) width=450;
    if(!height) height=400;

    if($('#divFrameResize').length<=0)
    {
        var fm = document.createElement('DIV');
        fm.id='divFrameResize';
        $('body').append(fm);
    }
    $('#divFrameResize').css({
        "position":"absolute",
        "background-color":'white',
        "border":"solid 2px gray",
        "top":src.offset().top + "px",
        "left":src.offset().left + "px",
        "width":src.width() + "px",
        "height":src.height() + "px"
    });
    
    var tar = $("#mcmm_dialog");
    tar.dialog(
    {
        bgiframe: true,
        modal: true,
        maxHeight: '600px',
        autoOpen:false,
        open: function(event, ui) {
            $(this).css({'max-height': 600, 'overflow-y': 'auto'}); 
        }
    });
    
    tar.dialog('option','title', title);
    tar.dialog('option','width', width + 'px');
    tar.dialog('option','maxHeight', '600px');
    //if(src.attr('height')) tar.dialog('option','height', height);
    
    tar.unbind('dialogclose');
    tar.bind('dialogclose',function(){
        $('#divFrameResize').animate({
            top:src.offset().top + "px",
            left:src.offset().left + "px",
            width:src.width() + "px",
            height:src.height() + "px"
        }, {
            duration: 200, 
            specialEasing: {
              width: 'swing',
              height: 'swing'
            }, 
            complete: function() {
                $(this).hide();
            }
        });
    });
    
    

    var tTop = (($(window).height()-height)/2)+$(window).scrollTop();
    var tLeft = (($(window).width()-width)/2)+$(window).scrollLeft();
    
    $('#divFrameResize').animate({
        top:tTop + "px",
        left:tLeft + "px",
        width:width + "px",
        height:height + "px"
      }, {
        duration: 200, 
        specialEasing: {
          width: 'swing',
          height: 'swing'
        }, 
        complete: function() {
            $(this).hide();
            tar.dialog('open');
        }
      });
}

/*****************************************************
    function to build the Move4Us calculator
    api url
******************************************************/
function GetPropParams()
{
    if($('#txtProp_SalePrice').length<=0) return;
    
    var propPrice = parseFloat($('#txtProp_SalePrice').val().replace(/[£,]/g,''));
    var agntCom = parseFloat($('#txtProp_Commission').val().replace('%',''));
    setCookie('txtProp_SalePrice',30);
    setCookie('txtProp_Commission',30);
    
    if(isNaN(propPrice))
    {
        $('#txtProp_SalePrice').val('£200,000.00')
        propPrice=200000;
    }
    if(isNaN(agntCom))
    {
        $('#txtProp_Commission').val('2%');
        agntCom=2;
    }
    return "saleprice={0}&commission={1}".format(propPrice, agntCom);
}

/*****************************************************
    Loading page to iframe
******************************************************/
function LoadPage(pageUrl)
{
    var bReturn = false;
    var oLeftSection = $('.LeftSection',$('div.PageContent'));
    if (oLeftSection.length<=0) 
    {
        $('div.BannerSection').remove();
        oLeftSection = $('div.LeftInnerSection_Large')
        oLeftSection.removeClass('LeftInnerSection_Large');
        oLeftSection.addClass('LeftSection');
        bReturn = true;
    }
    oLeftSection.empty();
    oLeftSection.html('<iframe frameborder="0" marginheight="0" marginwidth="0" ' +
        'id="pgProxy" src="{0}"></iframe>'.format(pageUrl));
        
    //If returned true, then the tab colouring need to be changed.
    return bReturn;
}

/*****************************************************
    Read and Write Cookies
******************************************************/
function setCookie(c_name, expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" + escape($('#' + c_name).val())+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            var sval = unescape(document.cookie.substring(c_start,c_end));
            if(sval)
                $('#' + c_name).val(sval);
        }
    }
    if($('#' + c_name).length>0)
        $("div[target='" + c_name + "']").slider('option', 'value', 
                        parseFloat($('#' + c_name).val().replace(/[£,%]/g,'')));
}

/*****************************************************
    Read and Write Cookies
******************************************************/
function submitDebtForm()
{
    document.getElementById('frmDebtAdvice').submit();   
}
