function chinAlign(){
    var c = dojo.query('#head .chin')[0];
    // Reset Div.chin left
    dojo.style(c, 'left', '0px');
    var l = (1024 - dojo.marginBox(c).w) / 2;
    dojo.style(c, 'left', l + 'px');
}


function showMenu(id){
    id = id || dojo.query('#head .head .select')[0].id;
    dojo.query('#head .head > div').removeClass('select');
    dojo.query('#' + id).addClass('select');
    dojo.query('#head .chin > div').addClass('hidden');
    dojo.query('#c' + id).removeClass('hidden');
    chinAlign(id);
    
    // Marquee Logo area
    //logo();
}


function selMenu(){
    dojo.query('#head .head > div')
        .connect('onmouseover', function(){
            showMenu(this.id);
        })
        .connect('onmouseout', function(){})
        .connect('onclick', function(){
            
        });
    dojo.query('#head .chin > div > div')
        .connect('onmouseover', function(){
            dojo.query('div', this.parentNode).removeClass('select');
            dojo.addClass(this, 'select');
        })
        .connect('onmouseout', function(){})
        .connect('onclick', function(){});
}


function calc(id, num){
    dojo.query('#mask').removeClass('hidden')
        /*.style('height', dojo.marginBox(document.body).h + 'px')*/;
    var ifr = dojo.query('#mask .mask iframe')[0].contentWindow;
    ifr.location.href = 'form_cal.php?RateID='+id+'&LoanPeriod='+num;
}



function hide(){
    dojo.query('#mask').addClass('hidden');
}


function ann(){
    var a = dojo.create('div');
    dojo.addClass(a, 'ann');
    dojo.place(a, dojo.byId('head'), 'last');
}


/**
 * logo
 * @param 
 */
function logo() {
    window.show = dojo.byId('logoshow');
    window.show1 = dojo.query('.show', window.show)[0];
    window.show2 = dojo.query('.show1', window.show)[0];
    show2.innerHTML = show1.innerHTML;
    
    window.marq = setInterval(marquee, 60);
    dojo.query('#logoshow')
        .connect('onmouseover', function(){
            clearInterval(marq);
        })
        .connect('onmouseout', function(){
            marq = setInterval(marquee, 60);
        });
}



/**
 * marque
 * @param 
 */
function marquee() {
    if((show2.offsetWidth - show.scrollLeft) <= 0){
        show.scrollLeft -= show1.offsetWidth;
    } else {
        show.scrollLeft++;
    }
}


function initializeMaps() {
    if (GBrowserIsCompatible()) {
        window.map = new GMap2(document.getElementById("maps"));
        map.setCenter(new GLatLng(1.2811, 103.8289), 18);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        // Add flag
        var point = new GLatLng(1.28115, 103.82885);
        var marker = new GMarker(point);
        //GEvent.addListener(map, 'click', function(){
            //var c = dojo.query('#content .address')[0].innerHTML;
            //map.openInfoWindow(point, dojo.query('#content .address')[0])
        //});
        map.addOverlay(marker);
        
        //GEvent.addListener(map, 'click', function(overlay, latlng, overlaylatlng) {
        //    console.log(map.getCenter(), map.getZoom(), latlng);
        //});
    }
}


/**
 * gotoMap
 * @param 
 */
function gotoMap() {
   map.panTo(new GLatLng(1.28115, 103.82885)); 
}


function GenerateLoanPercent(){
    form = document.forms[0];
        
    var PurchasePrice = form.purchase_price.value.replace(",","") 
    var LoanAmt = form.loan_amt.value.replace(",","") 
    var LoanPercent = form.loan_percent.value.replace(",","") 
    
    // 2 values is not allowed ..
    if (form.loan_amt.value !="" && form.loan_percent.value !=""){
        alert("Either Loan Amount or Loan Percent is allowed.\nPls Clear away one of the value .");
        form.loan_percent.focus();
        form.loan_percent.select();
        return false;
    }
    
    if (form.purchase_price.value !="" && form.loan_amt.value !=""){
        form.loan_percent.value = roundUp(((LoanAmt * 100)/PurchasePrice), 2)
        form.interest_amt.value = roundUp((LoanAmt * form.rate.value * form.loan_period.value)/100, 0)
        form.monthly_payment.value = roundUp((parseFloat(LoanAmt)+parseFloat(form.interest_amt.value))/(parseInt(form.loan_period.value) * 12), 0)

    }else{
        if (form.purchase_price.value !="" && form.loan_percent.value !=""){ 
            form.loan_amt.value = roundDown(((LoanPercent * PurchasePrice)/100), 0)
            LoanAmt = form.loan_amt.value
            form.interest_amt.value = roundUp((LoanAmt * form.rate.value * form.loan_period.value)/100, 0)
            form.monthly_payment.value = roundUp((parseFloat(LoanAmt)+parseFloat(form.interest_amt.value))/(parseInt(form.loan_period.value)* 12), 0)
        }
   }
}


function roundUp(value, precision)
{
    //eg , 1.2315 the result is still 1.24
    //eg , 1.2345 the result will be 1.24 for precision = 2
    // get the position no for the decimal pt 

    value = "" + value
     
    //get the position no for the decimal pt 	
  
    var decPoint = value.lastIndexOf(".")
    var tempstr = ""   
  
    decPoint = parseInt(decPoint)
    precision = parseInt(precision) 
    whole = "" + value
   
   
    var posWithPrecision = decPoint + precision              
        
    if(decPoint >= 0)
    {
            
            // ****  for precision = 0 for eg , 6.1 become 7 
            if (precision == 0){
                valueWithoutPrecision = whole.substring(0, decPoint);
                result = parseInt(valueWithoutPrecision) + 1
                return result
            }
            
                        
            // if data = 123.2 , we will append a 0 to it , thus result = 123.20
            // there should be at least 2 position after decimal pt  			
            ///////////////////////////////////////////////////////////////////////		
            /*	
            
            for(var i=0;i<precision;i++) {
                tempstr = tempstr + "0"
    
            }
            */
            //whole = whole + tempstr
                            
            prechar = whole.substring(posWithPrecision-1, posWithPrecision);
            curchar = whole.substring(posWithPrecision, posWithPrecision+1);
            nextchar = whole.substring(posWithPrecision+1,posWithPrecision+2);
                   
                        
            if (parseInt(nextchar) > 0){
                if (curchar=="9"){
                    valueWithPrecision = whole.substring(0, posWithPrecision-1);
                    prechar = parseInt(prechar) + 1
                    newchar  = prechar + 1 
                }else{
                    valueWithPrecision = whole.substring(0, posWithPrecision);			
                    newchar = parseInt(curchar) + 1
                    
                }
                result = valueWithPrecision + newchar
                
            }else{   // nextchar = 0
            
                result = whole.substring(0, posWithPrecision+1)
                
            }
            return result
                  
            
            
    }
    else
    {
            result = whole;
    }
    return result;
}


function roundDown(value, precision)
{
		//eg , 1.2315 the result is still 1.24
        //eg , 1.2345 the result will be 1.24 for precision = 2
       // get the position no for the decimal pt 
 
		value = "" + value
	 	
	   //get the position no for the decimal pt 	
	 
       var decPoint = value.lastIndexOf(".")
       var tempstr = ""   
     
       decPoint = parseInt(decPoint)
       precision = parseInt(precision) 
       whole = "" + value
       
       
       var posWithPrecision = decPoint + precision              
          	
        if(decPoint >= 0)
        {
				
				// ****  for precision = 0 for eg , 6.1 become 7 
				if (precision == 0){
					valueWithoutPrecision = whole.substring(0, decPoint);
					result = parseInt(valueWithoutPrecision) 
					return result
				}
				               
        }
        else
        {
                result = whole;
        }
        return result;
}


function Apply(){
    form = document.forms[0]

    if (isEmpty("purchase_price")){
        alert(EmptyMsg)
        return false
    }			
    
    if (!isCurrency("purchase_price")){
        alert(IsCurrencyMsg1)
        return false
    }
    
    if (isEmpty("loan_amt") || isEmpty("loan_percent") ){
        alert(EmptyMsg + "\nPlease remember to press the Calculate Loan Button after filling Loan Amount / Loan Percent." )
        return false
    }			
    
    if (!isCurrency("loan_amt")){
        alert(IsCurrencyMsg1)
        return false
    }

    if ( form.loan_percent.value > 100 ){
         alert(Max100Msg)
         return false
    }
    
    form.action="form_saloon.php"
    form.submit();
    //switch (form.hdCategory.value){
    //    case "WNC":
    //    {
    //        form.action="form_saloon.jsp"
    //        form.submit()
    //        break;
    //    }	
    //    case "WUC":
    //    {
    //        form.action="form_saloon.jsp"
    //        form.submit()
    //        break;
    //    }
    //    case "WNG":
    //    {
    //        form.action="form_comm.jsp"
    //        form.submit()
    //        break;
    //    }
    //    case "WUG":
    //    {
    //        form.action="form_comm.jsp"
    //        form.submit()
    //        break;
    //    }
    //    case "WNE":
    //        break;
    //        
    //    default:
    //        alert("default")
    //}
}


function isEmpty(FieldSelected) {
	//alert("form." + FieldSelected + ".value")
	if (eval("form." + FieldSelected + ".value") == ""){
		//alert("Empty")
		eval("form." + FieldSelected + ".focus()");
		eval("form." + FieldSelected + ".select()");
		//alert(EmptyMsg)
		return true;
	}
	return false;
}

function isCurrency(FieldName){
	form = document.forms[0]
	inputval = eval("form." + FieldName + ".value") ;
	
	oneComma=false;
	oneDecimal=false;
	j=0;
	k=3;
	
	inputStr=inputval.toString();
	for(var i = 0; i < inputStr.length; i++) {
		var oneChar=inputStr.charAt(i);
		if (oneChar=="." && !oneDecimal) {
			oneDecimal=true;
			k=j;
			j=1;
			continue; 
		}
		if (oneChar==",") {
			oneComma=true;
			j=0;
			continue;
		}
		j=j+1;
		if (oneChar< "0" || oneChar > "9") {
			eval("form." + FieldName +".focus()");
			eval("form." + FieldName +".select()");
			//alert(IsCurrencyMsg);
			return false;
		}
	}

	if (oneComma && (k!=3 || j!=3)) {
		eval("form." + FieldName +".focus()");
		eval("form." + FieldName +".select()");
		//alert(IsCurrencyMsg);
		return false;
	}
	if (oneComma && j!=3) {
		eval("form." + FieldName +".focus()");
		eval("form." + FieldName +".select()");
		//alert(IsCurrencyMsg);
		return false;
	}
	return true;
}


function showModel(){
    // veh_model
    dojo.query('#form1 select[name="auto_brand"]').connect('onchange', function(){
        var model = dojo.query('#form1 select[name="auto_model"]')[0];
        model.options.length = 1;
        var make = this.options[this.selectedIndex].value;
        var i = 1;
        dojo.forEach(veh_model, function(item){
            if(item['make'] == make){
                model.options[i] = new Option(item['model'], item['model']);
                i++;
            }
        });
        model.options[1].selected = true;
    })
}

