// http://flowplayer.org/tools/scrollable.html
// http://docs.jquery.com/UI/Slider
// http://datatables.net/
var dTable, prodform_index = 0,prodform_select_index = 0, slider1_value = 0, slider2_value = 0, filterby = new Array(), prodforms = new Array(), cc_forms = new Array(), filter_cc = 0, isSeek =1 , prev=-1; var amount, alert_flag = 0, click_flag = 0, mortgage_proportion = 4.5, dFlag1=true, year_index=0;

function  formatCurrency(num)
{
	//num = num.toString().replace(/$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-')  + num + ',' + cents);
}

function markPercentageDoubt(type, id)
{
	try {
	    var col = $e("doubtLink" + id);
	    col.innerHTML += '<b>!</b>';
	    col.removeChild(col.getElementsByTagName('a')[0]);
	}
	catch(err){}
}

function onSeek_common(index)
{
	$e('prodform_hidden').value = index;
	if(loans_page)
	{
		if(parseInt(cc_forms[index-1]) == 1)
	    {
	    	fnShow(12);
			fnShow(13);
			fnShow(16);
	    }
	    else
	    {
	    	fnHide(12);
			fnHide(13);
			fnHide(16);
	    }
	    loan_filter(index, parseInt($v('amount')));
	}
	else
		dTable.fnDraw();
}

function showall(ele)
{
	try
	{
		prodform_select_index =0;
		var items = $e('items').getElementsByTagName("a");
		for(i=0;i<items.length;i++)
		items[i].className='';
		ele.className = 'active';
		$("#prodformdescription").scrollable().seekTo(prodform_select_index);
		onSeek_common(prodform_select_index);
		isSeek =0;
	}
	catch(err)
	{

	}
}


function prodformClick(ele)
{
	try{
	var scroll_index = parseInt(ele.id);
	if(scroll_index == 0)
		$("#prodformselect").scrollable().seekTo(0);
	else
		$("#prodformselect").scrollable().seekTo(scroll_index);
	}
	catch(err){}
}
function syncronise1()
{
	if(isSeek)
	{
		prodform_select_index  = $("#prodformselect").scrollable().getIndex();
		var items_count = $("#prodformselect").scrollable().getSize();
		if((prodform_select_index <0) || (items_count - prodform_select_index == 4))
		{
			$("#prodformselect").scrollable().seekTo(0);
			return;
		}

		//console.debug('prodform_select_index' + prodform_select_index);

		var items = $e('items').getElementsByTagName("a");
		for(i=0;i<items.length;i++)
		items[i].className='';

		var eles = $("#prodformselect").scrollable().getItems();
		for(var i=0;i<eles.length;i++)
		{
			try{
			ele = eles[i].getElementsByTagName("a");
			if(parseInt(ele[0].id) == parseInt(prodform_select_index))
			{
				ele[0].className = 'active';
			}
			}
			catch(err){}
		}
		$("#prodformdescription").scrollable().seekTo(prodform_select_index);
		onSeek_common(prodform_select_index);
		isSeek =0;
	}
	else
		isSeek =1;
}

function syncronise()
{
	try
	{
    	if(isSeek)
    	{
    	prodform_select_index = $("#prodformdescription").scrollable().getIndex();
    	$("#prodformselect").scrollable().seekTo(prodform_select_index);
    	var items = $e('items').getElementsByTagName("a");
		for(i=0;i<items.length;i++)
		items[i].className='';

    	isSeek =0;
    	var eles = $("#prodformselect").scrollable().getItems();
		for(var i=0;i<eles.length;i++)
		{
			ele = eles[i].getElementsByTagName("a");
			if(parseInt(ele[0].id) == parseInt(prodform_select_index))
			{
				ele[0].className = 'active';
			}
		}
		onSeek_common(prodform_select_index);

    	}
    	else
    		isSeek =1;
	}catch(err){ }
}
function loan_filter(index, amt)
{
	var amount_integer= amt+'';
	amount_integer = amount_integer.replace('.','');
	amount_integer =  amount_integer.replace(',','.');
	amount_integer = parseInt( amount_integer);
	amount = parseInt(amount_integer);

	var max_amount = $e('max_amount').innerHTML;
	max_amount  = max_amount.replace('.','');
	max_amount  = max_amount .replace(',','.');
	max_amount  = parseInt(max_amount );

	if((amount_integer > max_amount) && max_amount>=0)
	{
		if(alert_flag==1)
		{
			failField('amount');
			$e('zero_slider_msg').style.display = 'none';
			$e('alert').style.display = '';
		}
	}
	else
	{
		removeClass($e('amount'),'error');
		$e('alert').style.display = 'none';

		if(isNaN(amount) && alert_flag==1)
			failField('amount');
	}
	if(max_amount<=0 && alert_flag==1 )
	{
		$e('alert').style.display = 'none';
		$e('zero_slider_msg').style.display = '';
	}
	else
		$e('zero_slider_msg').style.display = 'none';

    if (index >= -1) {
        prodform_index = index;
    }

    if (prodforms[prodform_index - 1] == filter_cc)
        return;

    dFlag = false;
    if (!prodform_index)
        dtFilter(0, amount);
    else
        dtFilter(prodforms[prodform_index - 1], amount);
}

function dtFilter(prodform, amount)
{
    filterby["prodform"] = prodform;
    filterby["amount"] = amount;
    filterby["perc"] = 0;
    filter_cc = 0;
    if (prodform) {
        for (i = 0; i < cc_forms.length; i++)
            if (cc_forms[i] == prodform)
                filter_cc = prodform;
    }
    if(dTable)
    	dTable.fnDraw();
}

function calc_amount()
{
    loan_filter(-2, $e('amount').value);
}
function remove_currency(str)
{
  var tmp = str.substring(2,(str.length-3));
  tmp = parseInt(tmp.replace(',',''));
  return tmp;
}

function fnShow( iCol )
{
	var bVis = dTable.fnSettings().aoColumns[iCol].bVisible;
	dTable.fnSetColumnVis( iCol, true );
}

function fnHide( iCol )
{
	try
	{
		var bVis = dTable.fnSettings().aoColumns[iCol].bVisible;
		dTable.fnSetColumnVis( iCol, false);
	}
	catch(err){}
}

function initLoans(){

    $(function(){

        $('#slider_income').slider({
            slide: function(event,ui) {
            alert_flag = 1;
			slider1_value =ui.value;
			$e('selected_income').innerHTML = formatCurrency(slider1_value);
            $e('total_income_post').value = slider1_value;
            var max_amount = ((42.5*(slider1_value-1000)+13295)-((33.35*slider2_value)));
            if(max_amount<0)
            	max_amount =0;
            $e('max_amount').innerHTML = formatCurrency(max_amount);
            $e('max_amount1').innerHTML = formatCurrency(max_amount);
    		},
			max:10000,
            step:50
        });
        $('#slider_housefee').slider({
            slide: function(event,ui) {
            alert_flag = 1;
			slider2_value =ui.value;
			document.getElementById('selected_housefee').innerHTML = formatCurrency(slider2_value);
            $e('housefee_post').value = slider2_value;
            var max_amount = ((42.5*(slider1_value-1000)+13295)-((33.35*slider2_value)));
            if(max_amount<0)
            	max_amount =0;
            $e('max_amount').innerHTML = formatCurrency(max_amount);
            $e('max_amount1').innerHTML = formatCurrency(max_amount);
    		},
			max:5000,
            step:50
        });

        $("#prodformselect").scrollable({
        	size:4,
        	vertical:true,
        	items:'#items',
        	loop:true,
        	onSeek: syncronise1,
        	clickable:false,
        	keyboard:false
        });
        $("#prodformdescription").scrollable({
            size: 1,
            onSeek: syncronise,
            loop:true,
            clickable:false,
            keyboard:false
        });
        //

        dTable = $('#data-table').dataTable({
            "aoColumns": [
            {
                "bSortable": false
            }, {
				 "bSearchable": false,
                "sType": "html"
            }, {
				"bVisible": false,
				"bSearchable": true,
                "sType": "html"
            }, {
                "bSearchable": true,
                "bVisible": false
            }, {
				 "bSearchable": false,
            	"sType": "html"
            }, {
				 "bVisible": false,
				 "bSearchable": true,
            	"sType": "html"
            },{
            	"sType": "title-numeric"
			 },{
            	 "bSortable": false
            }, {
            	"sType": "html"
            },{
                "bSearchable": false,
                "bVisible": false
            },{
                "bSearchable": false,
                "bVisible": false
            },{
                "bSearchable": false,
                "bVisible": false
            },{
                "bSearchable": false,
                "bVisible": false,
                "sType": "numeric"
            },{
                "bSearchable": false,
                "bVisible": false,
                "sType": "numeric-start"
            },{
                "bSortable": true,
                "bVisible": false,
                "sType": "numeric"
            },{
                "bVisible":false
            },{
            	"bSearchable": false,
                "bVisible": false,
                "sType": "numeric-start"
            }],
            "oLanguage": {
                "sSearch": "Zoek en beoordeel jouw product!:"
            },
			"iDisplayLength": 25,
			"aaSorting": [[ 6, "asc" ]],
            "fnRowCallback": function( nRow, aData, iDisplayIndex )
            {
	           	var intr;
				intr = getInterest(amount,aData[15],1);
				$('td:eq(3)', nRow).html('<span style="display:none;" >' + aData[15] + '</span>' + intr);
	           	return nRow;
            }
        });
    $.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex){
	if(parseInt(cc_forms[prodform_select_index-1]))
	{
		if((!parseInt(filterby["amount"]) || (parseInt(aData[12])) >= parseInt(filterby["amount"])) && parseInt(aData[3]) == parseInt(filterby["prodform"]))
        return true;
	}
	else
	{
    	if (!parseInt(filterby["amount"]) && !filterby["prodform"])
    	return true;

    	if(!parseInt(filterby["amount"]) && parseInt(aData[3]) == parseInt(filterby["prodform"]))
    	return true;

        if(parseInt(aData[3]) == parseInt(filterby["prodform"]) && (parseInt(aData[9]) <= parseInt(filterby["amount"])) && (parseInt(aData[10]) >= parseInt(filterby["amount"])))
        return true;

        if(!filterby["prodform"] && (parseInt(aData[9]) <= parseInt(filterby["amount"])) && (parseInt(aData[10]) >= parseInt(filterby["amount"])))
        return true;
    }
    return false;
    });

	     var tmp = parseInt(prodform);

        if(tmp)
			$("#prodformdescription").scrollable().seekTo(tmp);
		else
		{
			$("#prodformselect").scrollable().seekTo(2);
			$("#prodformselect").scrollable().seekTo(0);
		}

	});
}



	$.fn.dataTableExt.oSort['title-numeric-asc']  = function(a,b) {
		try{
		var x = a.match(/;">*(.*?)</)[1];
		var y = b.match(/;">*(.*?)</)[1];
		x = parseFloat(getInterest(amount,x ));
		y = parseFloat(getInterest(amount,y ));
		if(x == 0 )
			return 1;
		if(y == 0 )
			return -1;
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
		}
		catch(e)
		{
			return 0;
		}
	};
	$.fn.dataTableExt.oSort['title-numeric-desc'] = function(a,b) {
		try
		{
		var x = a.match(/;">*(.*?)</)[1];
		var y = b.match(/;">*(.*?)</)[1];
		x = parseFloat(getInterest(amount,x ));
		y = parseFloat(getInterest(amount,y ));
		if(x == 0 )
			return 1;
		if(y == 0 )
			return -1;
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));
		}
		catch(e)
		{
			return 0;
		}
	};
	$.fn.dataTableExt.oSort['numeric-start-asc']  = function(a,b) {
		var x = parseInt(a.split(' ')[0]);
		var y = parseInt(b.split(' ')[0]);
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};
	$.fn.dataTableExt.oSort['numeric-start-desc']  = function(a,b) {
		var x = parseInt(a.split(' ')[0]);
		var y = parseInt(b.split(' ')[0]);
		return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
	};

	$.fn.dataTableExt.aTypes.push(
	function ( sData )
	{
		var sValidChars = "0123456789-,";
		var Char;
		var bDecimal = false;


		for ( i=0 ; i<sData.length ; i++ )
		{
			Char = sData.charAt(i);
			if (sValidChars.indexOf(Char) == -1)
			{
				return null;
			}


			if ( Char == "," )
			{
				if ( bDecimal )
				{
					return null;
				}
				bDecimal = true;
			}
		}
		return 'numeric-comma';
	});


	$.fn.dataTableExt.oSort['numeric-comma-asc']  = function(a,b) {

		var x = (a == "-") ? 0 : a.replace( /,/, "." );
		var y = (b == "-") ? 0 : b.replace( /,/, "." );
		x = parseInt( x );
		y = parseInt( y );
		return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	};

	$.fn.dataTableExt.oSort['numeric-comma-desc'] = function(a,b) {
		var x = (a == "-") ? 0 : a.replace( /,/, "." );
		var y = (b == "-") ? 0 : b.replace( /,/, "." );

		x = parseInt( x );
		y = parseInt( y );
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));

	};

	  function post_to_url(url)
	{
		$e('form1').setAttribute("action",url);
		$e('form1').submit();
		return false;
	}

   var index =0;
    for(var i=0; i<prodforms.length; i++)
    {
    	if(prodforms[i] == parseInt('{{$smarty.request.prodform}}'))
    	{
    		index = i+1;
    		i = prodforms.length;
    	}
    }

function getInterest(amt, json, comma)
{
	var intr ='0,0';
	if(isNaN(amt))
		amt =0;

	var arr = eval('(' + json + ')');
	if(arr.perc.length && arr.min==null && arr.max==null)
		intr = arr.perc;  // In case Of Credit card
	else
	{
		if(arr.min)
		{
			if(arr.min.length)
			{
				if(amt)
				{
    				for(var i=0;i<arr.min.length;i++)
    				{
    					if(amt>=arr.min[i] && amt<=arr.max[i])
    					{
    						intr = arr.perc[i];
    						break;
    					}
    				}
				}
				else
					intr = arr.perc[0];
			}
		}
	}
	var str = intr;
	if(!comma)
		str = str.replace(',','.');
	return str;
}

/*****************************************************************************************************/
//Mortgages Page Related function
/*****************************************************************************************************/
	function amount_change()
	{
	  var amount = $e('amount').value;
	  $e('amount_post').value = amount;
	  if(amount>0)
	  {
		  $('#slider_income').slider('option', 'value', Math.round(amount/4.9));
		  $('#slider_borrowamount').slider('option', 'value', Math.round(amount/272.727));
		  $e('selected_income').innerHTML = formatCurrency(Math.round((amount/4.9)));
		  $e('selected_borrowamount').innerHTML =  formatCurrency(Math.round(amount/272.727)) ;
	  }
	}

	function getamount(event,ui)
	{
		slider1_value = ui.value;
		document.getElementById('selected_income').innerHTML =  formatCurrency(slider1_value) ;
		var result = (0.017966 * slider1_value).toFixed(2);
		$('#slider_borrowamount').slider('option', 'value', result );
		document.getElementById('selected_borrowamount').innerHTML =  formatCurrency(result);
		$e('amount').value = Math.round(slider1_value * (4.9)) ;
		$e('amount_post').value = Math.round(slider1_value * (4.9)) ;
	}

	function getamount1(event,ui)
	{
		slider2_value = ui.value;
		var result = (55.6594) * slider2_value;
		result = result.toFixed(2);
		document.getElementById('selected_borrowamount').innerHTML =  formatCurrency(slider2_value);
		$('#slider_income').slider('option', 'value', result);
		document.getElementById('selected_income').innerHTML =  formatCurrency(result) ;
		$e('amount').value = Math.round( slider2_value * (272.727));
		$e('amount_post').value = Math.round( slider2_value * (272.727));

	}

	function initLM(){
	    $(function(){

	    	$('#slider_income').slider({
	                slide: getamount,
					max:310000,
					step:5000,
					value:0
	            });
	        $('#slider_borrowamount').slider({
	                slide: getamount1,
					max:5500,
					step:50,
					value:0
	            });
	        $("#prodformselect").scrollable({
            	size:4,
            	vertical:true,
            	onSeek: syncronise1,
            	clickable:false,
            	loop:true
            });

            $("#prodformdescription").scrollable({
                size: 1,
                onSeek: syncronise,
                clickable:false,
                loop:true
            });

            //$("#prodformselect").scrollable().seekTo(0);


			 dTable = $('#data-table').dataTable( {
				"bProcessing": true,
				"bServerSide": true,
				"sAjaxSource": "content/mortAjax.php",
				"aaSorting": [[4, "asc" ]],
				"iDisplayLength": 25,
				"aoColumns": [
				{ "bSortable": false },
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				{"bSortable": false}
				]
				,
				"fnServerData": function ( sSource, aoData, fnCallback ) {
				/* Add some extra data to the sender */
				aoData.push( { "name": "prodform", "value": prodforms[prodform_select_index - 1]} );
				aoData.push( { "name": "years", "value": $v('years') } );
				$.getJSON( sSource, aoData, function (json) {
				/* Do whatever additional processing you want on the callback, then tell DataTables */

				fnCallback(json)
				tb_init('a.thickbox');
				} );
				}

			} );
		var index = parseInt(prodform);
	    $("#prodformdescription").scrollable().seekTo(index+1);

	    dFlag1 = false;
	        amount_change();

	 });
       $e('dtable-cont').style.display ='';

      	$.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex){
        /*if (!filterby["prodform"] &&  !(parseInt(aData[6]))||!filterby["prodform"] &&  (parseInt(aData[6])) == parseInt(filterby["year"]) || aData[2] == filterby["prodform"] && (parseInt(aData[6])) == parseInt(filterby["year"]) )
            return true;
        else
            return false;*/
        return true;
    });

	}
	/*******************************************************************************************/

