$(document).ready(function(){
    var phpName = location.pathname.substring(location.pathname.lastIndexOf("/")+1);
    if(phpName=="register.php"){
        $('.Captcha').sexyCaptcha('captcha.process.php');
    }
    
    if(phpName=="index.php" || phpName=="" || phpName=="advertise.php" || phpName=="recover.php"){
        $('.Captcha').sexyCaptcha('captcha.process.php');
    }
    
    if(phpName=="calls.php"){
        $(this).everyTime(1000,function(){
            for(var i=1;i<=$("#callscount").val();i++){
                expire = (parseInt($("#added_"+i).val()) + 86400)-(new Date().getTime())/1000;
                /*if(expire<0){
                    window.location.reload();
                }*/
                $("#expire_"+i).html(timeLeft(expire));
            }
        });
    }
    var selectText = "";
    var arrAirports = new Array;
    
    
    
    
    $(this).keypress(function(event) {
        $("#optionsDiv0 P A").css({"background-color":"","color":""});
        $(this).stopTime();
        if($("#optionsDiv0").css("display")!="none"){
            selectText += String.fromCharCode(event.which);
            var matches = pregmatch_in_array("^" + preg_quote(selectText),arrAirports);
            if(matches.length>0){
                $('#optionsDiv0').scrollTo("P A:eq("+matches[0]+")",300);
                $("#optionsDiv0 P A").eq(matches[0]).css({"color":"#ffffff","background-color":"#ec9a00"});
                $("#mySelectText0").html(arrAirports[matches[0]])
            }
            $(this).oneTime(500,function(){
                selectText = "";
            });
        }
    });
    
    $(this).everyTime(500,function(){
        if($("#optionsDiv0 P A").length>0){
            $("#optionsDiv0 P A").hover(function(){
               $("#optionsDiv0 P A").css({"background-color":"","color":""});
            });
            var counter = 0;
            $("#optionsDiv0 P A").each(function(){
                arrAirports[counter++] = $(this).html();
            });
            $(this).stopTime();
        }
    });
});

function submitReg(){
    
    var submit = true;
    var pass;
    var passconf;
    var mail;
    var elements = $("#formReg").serializeArray();
    for(var i=0; i<elements.length; i++){
        if(elements[i].value == "" && elements[i].name!="captcha") submit = false;
        if(elements[i].name=="password") pass = elements[i].value;
        if(elements[i].name=="passwordconfirm") passconf = elements[i].value;
        if(elements[i].name=="email") mail = elements[i].value;
    }
    
    if(!submit)
        alert("Don't leave any blank filed!");
    else if(parseInt($("#hackney_number").attr("value"))<=0 || isNaN($("#hackney_number").attr("value")) ){
        alert("Invalid hackney number!");
    }
    else{
        if(mail.search(/^[^.]+(\.[^.]+)*@([^.]+[.])+[a-z]{2,3}$/) != 0){
            alert("E-mail address is not valid!");
        }
        else if(pass != passconf){
            alert("Passwords doesn't match!");
        }
        else{
            document.formReg.submit();
        }
    }
}

function setCustomerData(){
    var datum = Date.parse($("#month").attr("value") + "/" + $("#day").attr("value") + "/" + $("#year").attr("value"));
    var now = new Date();
    
    if($("#from").attr("value")==0){
        alert("Please select airport!")
    }
    
    else if($("#to").attr("value")==""){
        alert("Please enter where you want to travel!");
    }
    
    else if((datum/1000) < (now.getTime()/1000)){
        alert("You have selected an invalid date!");
    }
    
    else{
        $("#airportSelect").slideUp("medium",function(){
            $("#customerData").slideDown("medium",function(){
               updateSelect(6);
            });
        });
    }
}

function saveTaxiCall(){
    
    if($("#name").attr("value")==""){
        alert("Name field is empty!");
    }
    else if($("#email").attr("value").search(/^[^.]+(\.[^.]+)*@([^.]+[.])+[a-z]{2,3}$/) != 0){
        alert("E-mail field is empty!");
    }
    else if($("#telephone").attr("value")==""){
        alert("Telephone field is empty!");
    }
    else if(parseInt($("#passengers").attr("value"))<=0 || isNaN($("#passengers").attr("value")) ){
        alert("Invalid passengers number!");
    }
    
    else{
        var jsonForm = $("#formTaxiCall").serialize();
        $.get("index.php?captcha=" + jsonForm.substring(jsonForm.lastIndexOf("&captcha=")+9),function(retval){
           if(retval != "1"){
                alert("Please drag and drop the correct shape into the space!");
           }
           else{
                $("#customerData").slideUp("medium",function(){
                    $.post("index.php?saveTaxiCall",$("#formTaxiCall").serialize(),function(retval){
                        if(retval=="1"){
                            $("#customerData").html("<br /><font color=\"black\"><b>Thank you, you will receive the 3 best quotes within 24 hours.</b></font>");
                            $("#customerData").slideDown("medium");
                        }
                        else if(retval=="0"){
                            $("#customerData").html("<font color=\"red\"><b>Unable to sent form!</b></font>");
                            $("#customerData").slideDown("medium");
                        }
                        else{
                            $("#customerData").html("<font color=\"red\"><b>" + retval + "</b></font>");
                            $("#customerData").slideDown("medium");
                        }
                    });
                });
           } 
        });
        
    }
}

function preg_quote (str, delimiter) {
    return (str+'').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\'+(delimiter || '')+'-]', 'g'), '\\$&');
}

function in_array(val,array){
    for(var i=0;i<array.length;i++){
        if(array[i]==val) return true;
    }
    return false;
}

function pregmatch_in_array(patter,array){
    var retval = new Array;
    var rg = new RegExp(patter,'i');
    var counter = 0;
    for(var i=0;i<array.length;i++){
        if(array[i].search(rg)>=0){
            retval[counter++] = i;
        }
    }
    return retval;
}

function checkform(form,dontCheck){
    if(dontCheck==null){
        var arrDCH = new Array();
    }
    else{
        var arrDCH = dontCheck.split(",");
    }
    
    var elements = $(form).serializeArray();
    var error = false;
    for(var i=0; i<elements.length; i++){
        if(elements[i].value=="" && !in_array(elements[i].name,arrDCH)){
            error = true;
        }
    }
    if(error){
        alert("Please don't leave any blank filed!");
        return false;
    }
    else{
        return true;
    }
    
}

function saveOffer(id){
    var price = $("#offer_" + id).val();
    if(!isNaN(price)){
        $.get("calls.php",{"id": id,"offer":price},function(retval){
            if(retval){
                $("#tdoffer_" + id).html("<b>&pound; "+price+"</b>");
                window.location.reload();
                
            }
            else{
                alert("Unable to save offer!");
            }
        });
    }
    else{
        alert("You typed invalid number!");
    }
}

function changePassword(){
    var currPass = $("#currPass").val();
    var Pass = $("#Pass").val();
    var PassAgain = $("#PassAgain").val();
    $.getJSON("calls.php",{"currPass" : currPass, "Pass":Pass, "PassAgain":PassAgain},function(retval){
        alert(retval.res);
        if(retval.success=="1"){
            $("#popup2").fadeOut("medium");
        }
    });
}

function reverse(){
    var fromContent = $("#fromDiv").html();
    var toContent = $("#toDiv").html();        
    if($("#fromDiv").attr("class")=="selectArea"){        
        $("#fromDiv").html(toContent);        
        $("#toDiv").html(fromContent);        
        $("#fromDiv").attr("class","input-way");
        $("#toDiv").attr("class","selectArea");  
        $("#reversed").val("1");                      
    } 
    else{
        $("#fromDiv").html(toContent);        
        $("#toDiv").html(fromContent);                
        $("#toDiv").attr("class","input-way");
        $("#fromDiv").attr("class","selectArea");        
        $("#reversed").val("0");    
    }  
    updateSelect(0);          
}

function timeLeft(sec){
    if(sec<0) sec=0;
    if(sec==0) return "EXPIRED!";
    var hour = parseInt(sec/3600); sec %= 3600;
    var minute = parseInt(sec/60); sec %= 60;
    sec = parseInt(sec);
    return (hour<10 ? "0" + hour : hour ) + " : " + (minute<10 ? "0" + minute : minute) + " : " + (sec<10 ? "0" + sec : sec);
}

function saveDetails(){
    $.post("calls.php?saveDetails",$("#detailsForm").serialize(),function(retval){
       alert(retval); 
    });
}

function chch(li,checked){
        $("#" + li + " INPUT[type='checkbox']").attr('checked', checked);
}

function saveSelectedAirports(){
     $.post("calls.php?setAirports",$("#airportsForm").serialize(),function(retval){
        alert(retval);
     });
}
