var dialogs = new Array();
function IsValidEmail(email){
  var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  return filter.test(email);
}
function dialogIt(msg, ttl, closeFunction, beforeCloseFunction) {
  var aDialog = $('<div class="alertDialog"></div>')
  .html('<div id="alertBox"><h1>'+ttl+'</h1><p>'+msg+'</p></div>').dialog({
    title: ttl,
    modal: true,
    resizable: false,
    minHeight: 50,
    buttons: {
      "OK": function() {
        aDialog.dialog("close");
      }
    },
    close: function() {
      for ( var x=0; x< dialogs.count; x++ ) {
        if ( dialogs[x] == aDialog ) {
          dialogs[x] = null;
        }
      }
    }
  });

  if ( !(!closeFunction) ) {
    $(aDialog).bind('dialogclose', closeFunction );
  }
  if ( !(!beforeCloseFunction) ) {
    $(aDialog).bind('dialogbeforeclose', beforeCloseFunction );
  }

  dialogs.push(aDialog);
}


$(document).ready(function() {
  $('#li-topcontact-6, #li-topcontact-7').css({
    'clear':'both',
    'display':'none'
  });
  $('#topContact_brochure').click(function() {
    if ( $('#li-topcontact-6').css('display') == 'none' ) {
      $('#li-topcontact-6, #li-topcontact-7').slideDown('fast');
    } else{
      $('#li-topcontact-6, #li-topcontact-7').slideUp('fast');
    }
  });
  $('#contactButton').toggle(
    function() {
      $('#contactButton').html('Close Panel').css({
        'background-position':'bottom'
      });
      $('#topContactForm').slideDown('fast');
    }, function() {
      $('#topContactForm').slideUp('fast');
      $('#contactButton').html('Contact Parklands').css({
        'background-position':'top'
      });
    }
    );
  if ( $('#topContactForm .error_list').length ) {
    $('#contactButton').click();
  }
  
  $('#contactForm #submit').click(function(e){
    if ( $('#contactForm #contact_name').val().length == '' || !IsValidEmail( $('#contactForm #contact_email').val() ) || $('#contactForm #contact_message').val().length == '' ) {
      e.preventDefault();
      dialogIt('Please enter your name, a valid email address and a message to continue','Enquiry Form');
      return false;
    }
    if ( $('#contactForm #contact_brochure:checked').length > 0 && $('#contactForm #contact_address').val().length < 1 ) {
      e.preventDefault();
      dialogIt('Please enter an address to deliver the brochure to','Enquiry Form');
      return false;
    }
  });

  $('#topContactForm #headSubmit').click(function(e){
    e.preventDefault();
    if ($('#topContact_dontfill').val().length < 1) {
      if ( $('#topContactForm #topContact_name').val().length == '' || !IsValidEmail( $('#topContactForm #topContact_email').val() ) || $('#topContactForm #topContact_message').val().length == '' ) {
        dialogIt('Please enter your name, a valid email address and a message to continue','Contacting Parklands');
        return false;
      }else if ( $('#contactForm #contact_brochure:checked').length > 0 && $('#contactForm #contact_address').val().length < 1 ) {
        dialogIt('Please enter an address to deliver the brochure to','Enquiry Form');
        return false;
      }else {
        $.post(
          '/contact-email',
          {
            n : $('#topContactForm #topContact_name').val(),
            e: $('#topContactForm #topContact_email').val(),
            m: $('#topContactForm #topContact_message').val(),
            s: $('#topContact_newsletter:checked').length
          },
          function (data,status) {
            if ( status == 'success' && data.ok ) {
              dialogIt('Thanks for your enquiry. We\'ll read it and get back to you as soon as possible.','Contacting Parklands');
            }else{
              dialogIt('Unfortunately there seemed to be a problem sending your enquiry. Please try again or drop us an email and let us know if the problem continues.','Contacting Parklands');
            }
            $('#contactButton').click();
          },
          'json'
          );
      }
    }
  });

  /* Footer Newsletter Signup */
  $('#emailSignup input[type=text]').bind('focus', function() {
    $(this).val('');
    $(this).unbind('focus');
  });

  $('#homeSubmit').click(function(e){
    e.preventDefault();
    
    if ($('#emailSignup_dontfill').val().length < 1) {
    
      if ( $('#emailSignup #name').val() == '' || $('#emailSignup #name').val() == 'Enter your name' ) {
        dialogIt('To be able to send you newsletters we need to know your name','Newsletter Signup')
        return false;
      }
      if ( $('#emailSignup #email').val() == '' || $('#emailSignup #email').val() == 'Enter you email address' || !IsValidEmail( $('#emailSignup #email').val() ) ) {
        dialogIt('To be able to send you newsletters we need a valid email address','Newsletter Signup')
        return false;
      }
      $.post(
        '/api-signup',
        {
          name : $('#name').val(), 
          email: $('#email').val()
        },
        function (data,status) {
          if ( status == 'success' && data.signupSuccess ) {
            dialogIt('Thank you for signing up to our email newsletter list.','Parklands Email Newsletter');
          }else{
            dialogIt('Unfortunately there seemed to be a problem adding you to the list. Please try again or drop us an email and let us know if the problem continues.','Parklands Email Newsletter');
          }
        },
        'json'
        );
    }
  });

  /* Explore Map Functionality */
  if ( $('#iMap').length ) {
    var leftIds = new String('|1|2|3|4|5|6|7|8|9|22|');

    $('#iMap a').click(function(e) {
      /* stop links being clicked */
      e.preventDefault();

      /* clear other active icons, activate this icon and display a loading gif */
      $('.soldActive').addClass('sold').removeClass('soldActive');
      $('.availableActive').addClass('available').removeClass('availableActive');
      $('.otherActive').addClass('other').removeClass('otherActive');
      $(this).attr('class', $(this).attr('class')+ 'Active');
      $('#loader').fadeIn('fast');

      /* remove any existing popups gracefully */
      if ( $('.homePop').length ) {
        var oldPop = $('.homePop');
        $(oldPop).each(function(i,el){
          $(el).find('.cycle').slideUp( 50, function() {
            setTimeout(function() {
              $(el).fadeOut('fast',function() {
                $(el).remove();
              });
            }, 50);
          });
        });
      }

      /* Get the id of the home */
      var id = $(this).attr('id').substr(3);

      /* Send a get to get the data from the db */
      $.get(
        '/load-home',
        {
          i: id
        },
        function(data, success) {
          /* if the data loaded ok */
          if ( success && data.ok ) {
            /* set horizontal position based on (fixed)id */
            var position = 'hpRight';
            if ( leftIds.indexOf('|'+id+'|') < 0 ) {
              position = 'hpLeft';
            }
            /* build the popup with the db data */
            var div = $('<div class="homePop '+ position +'"></div>');
            $(div).append('<h2>' + data.title + ( id != 22 ? '<br/>' + ( data.avail ? 'Available' : 'Sold' ) : '' ) + '</h2>');
            var imgDiv = $('<div class="cycle"></div>');
            for ( var i in data.images ) {
              $(imgDiv).append('<img src="/images' + data.images[i].src + '" alt="' + data.images[i].alt + '"/>');
            }
            $(div).append( $(imgDiv) );
            
            $(div).append( data.desc );
            $(div).append('<div id="popFoot"><a href="#">Close</a></div>');
            /* insert the popup */
            $('#iMap').append( $(div) );

            /* animate it in */
            setTimeout(function() {

              $(div).fadeIn('slow',function() {
                setTimeout(function() {
                  $(imgDiv).children(':first-child').slideDown( 450, function() {
                    if ( $(imgDiv).children().size() > 1 ) {
                      $('.cycle').trigger('popupCreated');
                    }
                  } );
                  $(div).children('*').slideDown( 450 );
                }, 100);
              })
              $('#loader').fadeOut('fast');
            }, 600);

            
            
            /* animate it out when close is clicked */
            $('#popFoot a').click(function(e) {
              e.preventDefault();
              setTimeout(function() {
                $('.homePop .cycle').children().slideUp( 700, function() {
                  setTimeout(function() {
                    $('.homePop').fadeOut('fast',function() {
                      $('.homePop').remove();
                    });
                  }, 200);
                });
                //                $('.homePop').children('*').slideUp( 700 );
                $('.homePop p').hide();
              }, 100);
            });
          }
        },
        'json'
        );
    })
  }

  if ( $('.zoomImg').length ) {
    $('.zoomImg').each(function() {
      var a = $('<a/>');
      $(a).attr({
        'rel':'lightbox-port', 
        'title':$(this).attr('title'), 
        'href':$(this).attr('src')
      });
      var clone = $(this).clone();
      $(a).append($(clone));

      $(this).replaceWith($(a));
    });
  }

  $('.cycle').live('popupCreated',function() {
    $(this).cycle({
      fx: 'fade',
      speed: 1000,
      delay: -4000,
      timeout: 7000
    });
  })

  if ( $('.hpCycle').length ) {
    $('.hpCycle').cycle({
      fx: 'fade',
      speed: 1000,
      timeout: 6000
    });
  }
});

