$(function(){
$('.moredetail').click(function() {
        var id=$(this).attr("id");
        $( "#moredetails"+id).dialog({
            width: 600
        });
    });
    $('.ui_button').button();
    $("#phone_num").click(function () {
        $("#show_phn").toggle();
    });
     $( "#end_date" ).datepicker({
        changeMonth: true,
        changeYear: true,
        minDate: 0,
        dateFormat: 'yy-mm-dd'
    });
    $("#email_id").click(function () {
        $("#show_email").toggle();
    });
    //More Button

    $("#searchsuburb").hide();
    $("#close_form_suburb").click(function() {
        $("#searchsuburb").hide();
        $("#mapSearch").show();
    });
    $("#state").change(function(){
        // get the selected option value of country
       var state = $("select[name='state']").val();
        $.ajax({
            url: 'getJSON.php',
            type: 'GET',
            data: ({
                'state':state,
                 'cmd':"getsuburbs"
            }),
            dataType: 'json',
            beforeSend: function(){
                jQuery("#ajaxLoader").show();
            },
            complete: function(){
                jQuery("#ajaxLoader").hide();
            },
            success: function(data) {
                var options = '';
                for (var i = 0; i < data.length; i++) {
                    options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $("select#suburb").html(options);
            }
        });
    });
    $("#type").change(function(){
        // get the selected option value of country
       var protype = $("select[name='type']").val();
        $.ajax({
            url: 'getJSON.php',
            type: 'GET',
            data: ({
                'protype':protype,
                'cmd':"getsubcats"
            }),
            dataType: 'json',
            beforeSend: function(){
                jQuery("#ajaxLoader2").show();
            },
            complete: function(){
                jQuery("#ajaxLoader2").hide();
            },
            success: function(data) {
                var options = '';
                for (var i = 0; i < data.length; i++) {
                    options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $("select#subprotype").html(options);
            }
        });
    });
    // update user profile
    $("#search_what").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "include/suburb.php",
                data: {
                    term: request.term
                //   country:  $("#usr_county").val()
                },
                dataType: "json",
                type: "GET",
                success: function(data){
                    response(data);
                }
            });
        },
        minLength: 2,
        select: function(event, ui) {
            $('#suburbid').val(ui.item.id);
        }
    });
    var runningRequest = false;
    var request;
        $("#search_btn").click(function() {
        var q = $("#search_what").val();

        if(q== ''){
            $('div#results').html('');
            return false;
        }
        //Abort opened requests to speed it up
        if(runningRequest){
            request.abort();
        }
        runningRequest=true;
        // THis needs to be changed to the location of the search.php file

        request = $.getJSON("search.php",{
            q:q,
            suburb:  $("#suburb").val(),
            property:  $("#property2").val(),
            search_price_min:  $("#search_price_min2").val(),
            search_price_max:  $("#search_price_max2").val()
        },function(data){
            showResults(data,q);
            runningRequest=false;
        });
        function showResults(data, highlight){
            $('#searchtxt').html('Your<span> Search Result</span>');
            var resultHtml = '';
            $.each(data, function(i,item){
                resultHtml+='<div class="listing_left_box">';
                resultHtml+='<div class="listing_details_left">';
                resultHtml+='<img src="lib/timthumb.php?src=uploads/'+item.photo+'&h=135&w=135"/></div>';
                resultHtml+='<div class="listing_details_right">';
                resultHtml+='<h1><a href="listdetails.php?id='+item.id+'">'+item.title+'</a></h1>';
                resultHtml+='<div class="clear"><div class="listing_box_left_div">Description:</div><div class="listing_box_right_div"> <p>'+item.content.replace(highlight, '<span class="highlight">'+highlight+'</span>')+'</p></div></div>';
                resultHtml+='</div></div>';
            });
            $(".right_div").hide();
            $('div#results').html(resultHtml);
        }

    });
    $("#dosearch_btn").click(function() {
        var q = $("#search_what").val();

        if(q== ''){
            $('div#results').html('');
            return false;
        }
        //Abort opened requests to speed it up
        if(runningRequest){
            request.abort();
        }
        runningRequest=true;
        // THis needs to be changed to the location of the search.php file

        request = $.getJSON("search.php",{
            q:q,
            suburb:  $("#suburbid").val(),
            property:  $("#property").val(),
            search_price_min:  $("#search_price_min").val(),
            search_price_max:  $("#search_price_max").val()
        },function(data){
            showResults(data,q);
            runningRequest=false;
        });
        function showResults(data, highlight){
            $('#searchtxt').html('Your<span> Search Result</span>');
            var resultHtml = '';
            $.each(data, function(i,item){
                resultHtml+='<div class="listing_left_box">';
                resultHtml+='<div class="listing_details_left">';
                resultHtml+='<img src="lib/timthumb.php?src=uploads/'+item.photo+'&h=135&w=135"/></div>';
                resultHtml+='<div class="listing_details_right">';
                resultHtml+='<h1><a href="listdetails.php?id='+item.id+'">'+item.title+'</a></h1>';
                resultHtml+='<div class="clear"><div class="listing_box_left_div">Description:</div><div class="listing_box_right_div"> <p>'+item.content.replace(highlight, '<span class="highlight">'+highlight+'</span>')+'</p></div></div>';
                resultHtml+='</div></div>';
            });
            $(".right_div").hide();
            $('div#results').html(resultHtml);
        }

    });

    $('input#search_what').keyup(function(e){
        e.preventDefault();
        var $q = $(this);

        if($q.val() == ''){
            $('div#results').html('');
            return false;
        }
        //Abort opened requests to speed it up
        if(runningRequest){
            request.abort();
        }
        runningRequest=true;
        // THis needs to be changed to the location of the search.php file

        request = $.getJSON("search.php",{
            q:$q.val()
        },function(data){
            showResults(data,$q.val());
            runningRequest=false;
        });

        function showResults(data, highlight){
            $('#searchtxt').html('Your<span> Search Result</span>');
            var resultHtml = '';
            $.each(data, function(i,item){
                resultHtml+='<div class="listing_left_box">';
                resultHtml+='<div class="listing_details_left">';
                resultHtml+='<img src="lib/timthumb.php?src=uploads/'+item.photo+'&h=135&w=135"/></div>';
                resultHtml+='<div class="listing_details_right">';
                resultHtml+='<h1><a href="listdetails.php?id='+item.id+'">'+item.title+'</a></h1>';
                resultHtml+='<div class="clear"><div class="listing_box_left_div">Description:</div><div class="listing_box_right_div"> <p>'+item.content.replace(highlight, '<span class="highlight">'+highlight+'</span>')+'</p></div></div>';
                resultHtml+='</div></div>';
            });
            $(".right_div").hide();
            $('div#results').html(resultHtml);
        }

        $('form').submit(function(e){
            e.preventDefault();
        });
    });
    $('.rmv-dft-val').click(
        function() {
            if (this.value == this.defaultValue) {
                this.value = '';
            }
        }
        );
    $('.rmv-dft-val').blur(
        function() {
            if (this.value == '') {
                this.value = this.defaultValue;
            }
        }
        );
    $('#photoimg').live('change', function(){
        $("#preview").html('');
        $("#preview").html('<img src="images/ajax-loader.gif" alt="Uploading...."/>');
        $("#imageform").ajaxForm({
            target: '#preview'
        }).submit();

    });
    $('#photoimglogo').live('change', function(){
        $("#previewlogo").html('');
        $("#previewlogo").html('<img src="images/ajax-loader.gif" alt="Uploading...."/>');
        $("#imageformlogo").ajaxForm({
            target: '#previewlogo'
        }).submit();

    });

    /* $('#state').chainSelect('#suburb','getSVB.php',
    {
        before:function (target) //before request hide the target combobox and display the loading message
        {
            $("#loading_global").css("display","block");
            $(target).css("display","none");
        },
        after:function (target) //after request show the target combobox and hide the loading message
        {
            $("#loading_global").css("display","none");
            $(target).css("display","inline");
        }
    });*/

    $('#regform').submit(function(e) {
        register();
        e.preventDefault();
    });
    $('#updateacount').ajaxForm({
        beforeSubmit: function() {
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        type: "POST",
        url: "updatelist.php?cmd=updatprofile",
        data: $('#updateacount').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#error').html(data.msg).css('visibility','visible');
            }
            else{
                $('#error').html(data.msg).css('visibility','visible');
            }
        }
    });
    $('#sendNewsletter').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass("errormsg");
        },
        type: "POST",
        url: "submit.php?cmd=sendnewsletter",
        data: $('#sendNewsletter').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass("errormsg");
            }
            else{
                $('#result').html(data.msg).addClass("success");
            }
        }
    });
    $('#contactForm').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass('errormsg');
        },
        type: "POST",
        url: "submit.php?cmd=contactagent",
        data: $('#contactForm').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass('errormsg');
            }
            else{
                $('#contactForm').hide();
                $('#result').html(data.msg).addClass('success');

            }
        }
    });
    $('#contactUs').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass('errormsg');
        },
        type: "POST",
        url: "submit.php?cmd=contactus",
        data: $('#contactUs').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass('errormsg');
            }
            else{
                $('#contactForm').hide();
                $('#result').html(data.msg).addClass('success');

            }
        }
    });
    $('#addtelemarketerForm').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass('errormsg');
        },
        type: "POST",
        url: "submit.php?cmd=addtelemarketer",
        data: $('#addtelemarketerForm').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass('errormsg');
            }
            else{
                $('#result').html(data.msg).addClass('success');

            }
        }
    });
    $('#changepassForm').ajaxForm({
        beforeSubmit: function() {
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        type: "POST",
        url: "updatelist.php?cmd=changepass",
        data: $('#changepassForm').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#error').html(data.msg).css('visibility','visible');
            }
            else{
                $('#error').html(data.msg).css('visibility','visible');
            }
        }
    });

    $('#forgotpassForm').ajaxForm({
        beforeSubmit: function() {
            //  hideshow('loading',1);
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        type: "GET",
        url: "submit.php?cmd=forgot",
        data: $('#forgotpassForm').serialize(),
        dataType: "json",
        success: function(data) {
            if(parseInt(data.status)==1)
            {

                $('#error').html(data.txt).css('visibility','visible');
            }
            else if(parseInt(data.status)==0)
            {
                $('#error').html(data.txt).css('visibility','visible');

            }
        //   $('#error').html("Please Wait...").css('visibility','hidden');
        }
    });
    // Un sub from user
    $('#unsubForm').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass('errormsg');
        },
        type: "POST",
        url: "submit.php?cmd=unsub",
        data: $('#unsubForm').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass('errormsg');
            }
            else{
                $('#result').html(data.msg).addClass('success');

            }
        }
    });
    $('#addoperator').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").addClass('errormsg');
        },
        type: "POST",
        url: "submit.php?cmd=addoperator",
        data: $('#addoperator').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#result').html(data.msg).addClass('errormsg');
            }
            else{
                $('#result').html(data.msg).addClass('success');

            }
        }
    });
    $('#addcontactForm').ajaxForm({
        beforeSubmit: function() {
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        type: "POST",
        url: "submit.php?cmd=addcontact",
        data: $('#addcontactForm').serialize(),
        dataType: "json",
        resetForm:true,
        success: function(data) {
            if (data.error === true) {
                $('#error').html(data.msg).css('visibility','visible');
            }
            else{
                $('#error').html(data.msg).css('visibility','visible');
            }
        }
    });
    $('#editcontactForm').ajaxForm({
        beforeSubmit: function() {
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        type: "POST",
        url: "updatelist.php?cmd=updatecontact",
        data: $('#editcontactForm').serialize(),
        dataType: "json",
        success: function(data) {
            if (data.error === true) {
                $('#error').html(data.msg).css('visibility','visible');
            }
            else{
                $('#error').html(data.msg).css('visibility','visible');
            }
        }
    });
    $('#updatelist2').ajaxForm({
        beforeSubmit: function() {
            $('#result').html("Please Wait...").css('color','red');
        },
        url: "updatelist.php?cmd=updatelist",
        dataType : 'json',
        type:"POST",
        data:$('#updatelist2').serialize(),
        success: function(data) {
             if (data.error === true) {
               $('#result').html(data.msg).addClass('errormsg');
            }
            else
            {
                 $('#result').html(data.msg).addClass('success');
            }

        }
    });
    $('#updatelist').ajaxForm({
        beforeSubmit: function() {
            $('#error').html("Please Wait...").css('visibility','visible');
        },
        url: "updatelist.php?cmd=updatelist",
        dataType : 'json',
        type:"POST",
        data:$('#updatelist').serialize(),
        success: function(data) {
            if(parseInt(data.status)==1)
            {

                $('#error').html(data.txt).css('visibility','visible');
            }
            else if(parseInt(data.status)==0)
            {
                $('#error').html(data.txt).css('visibility','visible');

            }

        }
    });

    $('#listform').ajaxForm({
        beforeSubmit: function() {
            hideshow('loading',1);
        },
        dataType : 'json',
        success: function(data) {
            if(parseInt(data.status)==1)
            {
                window.location=data.txt;
            }
            else if(parseInt(data.status)==0)
            {
                error(1,data.txt);
            }
            hideshow('loading',0);
        }
    });

    $('#doLogin').click(function(e) {
        login();
        e.preventDefault();

    });
    initPagination();
});
function pageselectCallback(page_index, jq){
    var new_content = jQuery('#hideout div.listing_left_box:eq('+page_index+')').clone();
    $('#Searchresult').empty().append(new_content);
    $('#hideout').hide();
    return false;
}

/**
             * Initialisation function for pagination
             */
function initPagination() {
    // count entries inside the hidden content
    var num_entries = jQuery('#hideout div.listing_left_box').length;
    // Create content inside pagination element
    $("#Pagination").pagination(num_entries, {
        callback: pageselectCallback,
        items_per_page:1, // Show only one item per page
        num_edge_entries: 2,
        num_display_entries: 8
    });
}
function login()
{
    hideshow('loading',1);
    error(0);
    $.ajax({
        type: "POST",
        url: "submit.php?cmd=login",
        data: $('#loginform').serialize(),
        dataType: "json",
        success: function(msg){

            if(parseInt(msg.status)==1)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==0)
            {
                error(1,msg.txt);
            }
            hideshow('loading',0);
        }
    });


}
function register()
{
    hideshow('loading',1);
    error(0);

    $.ajax({
        type: "POST",
        url: "submit.php?cmd=register",
        data: $('#regform').serialize(),
        dataType: "json",
        success: function(msg){

            if(parseInt(msg.status)==1)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==0)
            {
                error(1,msg.txt);
            }
            hideshow('loading',0);
        }
    });


}
function updatefunction()
{
    hideshow('loading',1);
    error(0);
    $.ajax({
        type: "POST",
        url: "updatelist.php",
        data: $('#updatelist').serialize(),
        dataType: "json",
        success: function(msg){

            if(parseInt(msg.status)==1)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==0)
            {
                error(1,msg.txt);
            }
            hideshow('loading',0);
        }
    });

}

function hideshow(el,act)
{
    if(act) $('#'+el).css('visibility','visible');
    else $('#'+el).css('visibility','hidden');
}

function error(act,txt)
{
    hideshow('error',act);
    if(txt) $('#error').html(txt);
}
function getSuburb(item){
    var state=$(item).attr("id");
    $.ajax({
        url: 'getJSON.php?cmd=getsuburbs',
        type: 'get',
        data: ({
            'state':state
        }),
        dataType: 'json',
        beforeSend: function(){
            jQuery("#ajaxLoader").show();
        },
        complete: function(){
            jQuery("#ajaxLoader").hide();
            $("#mapSearch").hide();
            $("#loading_global").css("display","block");
            $("#ajaxloader").css("display","block");
            $("#searchsuburb").show();
        },
        success: function(data) {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
            }
            $("select#suburb").html(options);
            $('#mapSearch').focus();
            $("#loading_global").css("display","none");
        }
    });
}
function getListings(){
    var state=$(item).attr("id");
    $.ajax({
        url: 'getJSON.php?cmd=getsuburbs',
        type: 'get',
        data: ({
            'state':state
        }),
        dataType: 'json',
        beforeSend: function(){
            jQuery("#ajaxLoader").show();
        },
        complete: function(){
            jQuery("#ajaxLoader").hide();
            $("#mapSearch").hide('slow');
            $("#loading_global").css("display","block");
            $("#ajaxloader").css("display","block");
            $("#searchsuburb").show('slide', {
                direction: 'left'
            }, 1000);
        },
        success: function(data) {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
            }
            $("select#suburb").html(options);
            $('#mapSearch').focus();
            $("#loading_global").css("display","none");
        }
    });
}
