function createPopup(title,html,options)
{
  var opt=typeof(options)=='undefined' ? {modal:true,width:'auto'} : options;   
  if (!opt.close)
    opt.close=function(event,ui) { $(this).remove(); };
  if (!opt.buttons)
    opt.buttons= { "Close": function() { $(this).dialog("close"); } };
      
  $('<div title="'+title+'"><p>'+html+'</p></div>').dialog(opt);      
} 

function doQuickSearch()
{
  var f=document.forms['qs'];
  if (f.suburb.value=='')
    createPopup("Can't perform search","Please enter a suburb to search and optionally a radius around the suburb to search.")
  else
    f.submit();  
}

function init_apage() 
{
   $('#tabs').tabs({
       select: function(event,ui) {
         document.location=$(ui.tab).attr('href');
       },
       show: function(event,ui) {
            var tab=$(ui.tab);
            var s;
            if (tab.attr('loaded'))
              return;
            if ((s=tab.html())=='Current Listings')
              $(ui.panel).load('/_ajax.current-listings.html',{id:agentID},function() { tab.attr('loaded',1);init_shortlist(0);});
            else if (s=='Sold Properties')
              $(ui.panel).load('/_ajax.sold-listings.html',{id:agentID},function() { tab.attr('loaded',1);});
            else if (s=='Testimonials')
              $(ui.panel).load('/_ajax.agent-testimonials.html',{id:agentID},function() { tab.attr('loaded',1);testimonial_load(); });
          }
       });
}

function testimonial_load()
{
  $('.testimonial div.inner > div > p').each(function() {
    if ($(this).height() < $(this).parent().height()) {
      $(this).parent().css({height: 'auto',overflow: 'visible'}).next().detach();    
    }    
  });
  
  $('.testimonial div.inner > a').click(function() {
    $(this).prev().css('overflow','visible').css('height','auto');  
    $(this).detach(); 
    return false; 
  });    
}


function validate_appraisal()
{
  var error=''; 
  var f=document.forms['appraisal_form'];
  if (f.name.value=='')
    error='<li>Please enter your name</li>';
  if (f.phone.value=='')
    error+='<li>Please enter your phone number</li>';
  if (f.email.value=='' || !validateEmailv2(f.email.value))
    error+='<li>Please enter a valid email address</li>';
  if (error.length) {
    createPopup('Unable to Send Details','Please correct the following and try again -<ul>'+error+'</ul>');
  }       
  else
    f.submit();
}

function validate_contactform()
{
  var error=''; 
  var f=document.forms['contact_form'];
  if (f.name.value=='')
    error='<li>Please enter your name</li>';
  if (f.phone.value=='')
    error+='<li>Please enter your phone number</li>';
  if (f.email.value=='' || !validateEmailv2(f.email.value))
    error+='<li>Please enter a valid email address</li>';
  if (error.length) {
    createPopup('Unable to Submit Enquiry','Please correct the following and try again -<ul>'+error+'</ul>');
  }       
  else
    f.submit();
}

function validate_wanted()
{
  var error=''; 
  var f=document.forms['wanted_form'];
  if (f.name.value=='')
    error='<li>Please enter your name</li>';
  if (f.phone.value=='')
    error+='<li>Please enter your phone number</li>';
  if (f.email.value=='' || !validateEmailv2(f.email.value))
    error+='<li>Please enter a valid email address</li>';
  if (error.length) {
    createPopup('Unable to Send Details','Please correct the following and try again -<ul>'+error+'</ul>');
  }       
  else
    f.submit();
}

function validateEmailv2(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    if(email.length <= 0)
    {
      return true;
    }
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
        var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
        if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}


 function send_shortlist()
 {
    var error='';
    var f=$('form[name="shortlist"]');
    if (f[0].email.value=='' || !validateEmailv2(f[0].email.value))
      error+='<li>Please enter a valid email address for your email</li>';
    if (error.length) {
      createPopup('Unable to Send Shortlist','Please correct the following items - <ul>'+error+'</ul>');
      return false;    
    }   
    var sending=$('<div title="Sending Your Shortlist"><p>Please wait while your shortlist email is sent.</p></div>').dialog({modal:true,width:'auto',resizable:false,closeOnEscape:false});
    $.ajax({
        url:'/_ajax.email-shortlist.html',
        data: f.serialize(),
        type: 'POST',
        complete: function(xhr,status) {
          sending.remove();
          if (status=='success') {    
            $('#shortlist-popup').remove();
            createPopup('Shortlist Sent Successfully','Your shortlist has been successfully sent.');
          }
          else
            createPopup('Error Sending Shortlist','There was a problem sending the email.  Check the email addresses and try again.');
            
        }
    }); 
   return false;        
 }
 
function init_shortlist_page()
{
  init_shortlist(1);
  $('#email_s').click(function() {
    if (!$('#shortlist-popup').dialog('open').length)
      $.ajax({
          url: '/_ajax.shortlist-popup.html',
          success: function(data,status,xhr) {
            $(data).dialog({modal:false,width:'auto',height:'auto'}).find('a.button').click(send_shortlist);
          }
      });  
    return false;    
  });    
}

function init_shortlist(delOnRem)
{
    
  $('a.shortlist').click(function() {
    var btn=$(this);  
    $.ajax({
        url: '/_ajax.shortlist.html',
        data: {id: btn.attr('ref') },
        success: function(data,status,xhr) {
            $('#shortlist').html(data);
            var id=parseInt(xhr.getResponseHeader('X-ID'));
            if (id < 0) {
              createPopup("Property Removed from Shortlist","The property has been removed from your shortlist.");
              if (delOnRem)
                btn.parents('div.prop_box').detach();
              else
                btn.attr('ref',-1*id).children('span').html('<img src="/images/shortlist.png" /> Add to Shortlist');
            }  
            else {
              createPopup("Property Added to Shortlist","The property has been added to your shortlist.");
              btn.attr('ref',-1*id).children('span').html('<img src="/images/shortlist_r.png" /> Remove Shortlist');
            }  
        },
        error: function(xhr,status) {
            createPopup("Unable to Add To Shortlist","There was an error trying to add the property to your shortlist.  Try again");
        }
    });    
    return false;  
  }); 
  $('a.button_b.sms').click(function() {
      var id=$(this).attr('ref');
        $.ajax({
            url: '/_ajax.sms.html',
            data: {'id':id},
            success: function(data,xhr,status) {
              $(data).dialog({modal:false,width:'auto',height:'auto',close:function() { $(this).remove();}}).find('a.button').click(send_sms);
            }
        });
      return false;
  });
   
}

function send_sms()
{
  var f=document.forms['sms'];
  var error='';
  var m=f.mobile.value.replace(/\s/g,'');
  
  if (f.name.value=='')
    error='<li>Please enter your name</li>';
  if (!/^0(1|4|5)\d{8}$/.test(m))
    error+='<li>Please enter a valid Australian mobile number</li>';
  if (error.length) {
    createPopup('Unable to send SMS','Please correct the following and try again - <ul>'+error+'</ul>');
    return false;      
  }  
    var sending=$('<div title="Sending SMS"><p>Please wait while your SMS is sent.</p></div>').dialog({modal:true,width:'auto',resizable:false,closeOnEscape:false});
    $.ajax({
        url:'/_ajax.send-sms.html',
        data: $(f).serialize(),
        type: 'POST',
        complete: function(xhr,status) {
          sending.remove();
          if (status=='success') {    
            createPopup('SMS Sent Successfully','YourSMS has been successfully sent to your mobile phone.');
            $('#sms-popup').remove();
          }
          else
            createPopup('Error Sending SMS','There was a problem sending your SMS.  Check your mobile number and try again.');
        }
    }); 
  return false;
}

 function init_property_page(listingID)
 {
   init_shortlist(0);
   $('#tabs').tabs({
       show: function(event,ui) {
            if ($(ui.tab).html()=='Map' && !gmap)
              init_map();
          }
       });
  show_image(firstPhoto);     
  var i=$('#offer > iframe');
  if (i.length)
    i[0].src='https://www.offernow.com.au/offer.php?c=1&x='+listingID;       
  $('#thumbs a.nav').click(function() {
      // scroll...
      var d=$('#thumbs div.content > div');
      var m=parseInt(d.css('margin-left'));
      if ($(this).hasClass('left')) {
        if (m < 0) 
          d.css('margin-left',m+76+'px');
      }
      else if (-m < d.width()-700)
        d.css('margin-left',parseInt(d.css('margin-left'))-76+'px');
      else
        d.css('margin-left','0px');  
      return false;  
  });
  $('#thumbs div.content div a').click(function() {
    show_image($(this).attr('pi'));  
    return false;  
  });
  $('#gallery-m a.nav').click(function() {
    var pim=$('#thumbs div.content a[pi="'+$('#gallery-m > img').attr('pi')+'"]');  
    if ($(this).hasClass('left')) {
      show_image(pim.prev().attr('pi'));    
    }  
    else {
      show_image(pim.next().attr('pi'));    
    }
    return false;    
  });
  // forms
  $('form[name="talk"] a').click(function() {
    
    var f=$('form[name="talk"]');
    var error='';
    // basic validation
    if (f[0].name.value < 2) 
      error='<li>Please enter your name</li>';
    if (f[0].email.value=='' || !validateEmailv2(f[0].email.value)) 
      error+='<li>Please enter a valid email address</li>';
    if (f[0].about.selectedIndex <= 0)
      error+='<li>Please select the most appropriate option for About You</li>';
    if (error.length) {
      createPopup('Unable to Send Message','Please correct the following items - <ul>'+error+'</ul>');
      return false;
    }  
    var sending=$('<div title="Sending to Agent"><p>Please wait while your query is sent to the agent.</p></div>').dialog({modal:true,width:'auto',resizable:false,closeOnEscape:false});      
    $.ajax({
        url:'/_ajax.talk.html',
        type:'POST',
        data: f.serialize(),
        complete: function(xhr,status) {
          sending.remove();
          if (status=='success') {
            $('#agent-form').html('<h3>Thank you. Message Sent</h3><p>Your message has been successfully sent to the agent and they will contact you shortly.</p>');    
            createPopup('Message Sent Successfully','Your message has been successfully sent to the agent and they will contact you shortly.');
          }
          else
            createPopup('Error Sending Message','There was a problem sending your query to the agent. Please try again in a moment');
        }
    });   
    return false; 
  });
  $('a.button_b.friend').click(function() {
      if (!$('#friend-popup').dialog('open').length)
        $.ajax({
            url: '/_ajax.friend.html',
            data: {'id': id},
            success: function(data,xhr,status) {
              $(data).dialog({modal:false,width:'auto',height:'auto'}).find('a.button').click(send_to_friend);
            }
        });
      return false;
  });
 }
 
 function send_to_friend()
 {
    var error='';
    var f=$('form[name="friend"]');
    if (f[0].name.value.length < 2)
      error='<li>Please enter your name</li>';
    if (f[0].email.value=='' || !validateEmailv2(f[0].email.value))
      error+='<li>Please enter a valid email address for your email</li>';
    if (f[0].femail.value=='' || !validateEmailv2(f[0].femail.value))
      error+='<li>Please enter a valid email address for your friends email</li>';
    if (error.length) {
      createPopup('Unable to Send Message','Please correct the following items - <ul>'+error+'</ul>');
      return false;    
    }   
    var sending=$('<div title="Sending to Your Friend"><p>Please wait while your email is sent.</p></div>').dialog({modal:true,width:'auto',resizable:false,closeOnEscape:false});
    $.ajax({
        url:'/_ajax.email-friend.html',
        data: f.serialize(),
        type: 'POST',
        complete: function(xhr,status) {
          sending.remove();
          if (status=='success') {    
            createPopup('Message Sent Successfully','Your message has been successfully sent to your friend.');
            $('#friend-popup').remove();
          }
          else
            createPopup('Error Sending Message','There was a problem sending the email to your friend.  Check the email addresses and try again.');
            
        }
    }); 
   return false;        
 }

 
// jquery plug in to rotate images
// options
//      - base: base image name eg. 'images/slideshow/image_'
//      - ext: file extension for all images eg. 'jpg'
//      - num: number of sequential images in slideshow eg. 10
//      - images: array of image names if not using sequential type option as above

(function($) 
{
    $.fn.jcsSlideshow = function(options)
    {
        return this.each(function() 
        {
          if (options.num) { 
            options.images=[];  
            for (var i=1; i <= options.num; i++)
              options.images.push(options.base+i+'.'+options.ext);
          }    
          if (!options.index)
            options.index=1;
          this.jcsSlideShow={'options': options,images: []};  
          var e=this;    
          this.jcsSlideShow.loaded=function(src) {
            for (var i=0; i < this.images.length; i++)
              if (this.images[i].src.indexOf(src) >= 0)
                return this.images[i];
            return null;        
          }
          this.jcsSlideShow.show=function(img) {
              $(e).hide(e.jcsSlideShow.options.effectOut,{},e.jcsSlideShow.options.effectOutSpeed,function() {
                this.src=img.src;
                $(this).show(e.jcsSlideShow.options.effectIn,{},e.jcsSlideShow.options.effectInSpeed,function() {
                 window.setTimeout(function() { e.onjcsSlideshowChange(); },e.jcsSlideShow.options.delay);   
                })    
              });          
              
          }
          
          // in theory we should only have one slideshow bound to one element....
          this.onjcsSlideshowChange=function() {
            if (this.jcsSlideShow.options.index >= this.jcsSlideShow.options.images.length)
              this.jcsSlideShow.options.index=1;
            else
              this.jcsSlideShow.options.index++;
            var e=this;
            var img;
            var src=this.jcsSlideShow.options.images[this.jcsSlideShow.options.index-1];
            if ((img=this.jcsSlideShow.loaded(src))) {
              this.jcsSlideShow.show(img);
            } 
            else {
              img=new Image;
              $(img).load(function() {
                e.jcsSlideShow.show(this);
                e.jcsSlideShow.images.push(this);
              });  
              img.src=src;
            } 
          }
          window.setTimeout(function() { e.onjcsSlideshowChange(); },this.jcsSlideShow.options.delay);   
        });
    };
})(jQuery); // pass the jQuery object to this function


