/** vj global
/** based on http://www.dustindiaz.com/namespace-your-javascript/
/** adding private properties and methods **/

$.fn.clearOnFocus = function () {
    this.blur(function () {
        if (!this.value) {
            this.value = this.defaultValue;
        }
        $(this).animate({ width: '70px' }, 200);
    }).focus(function () {
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        $(this).animate({ width: '156px' }, 200);
    });
};

var lendlease = (function () {
    var servicePoints = {
        'setHouseAndLandCookie': '/Services/HouseAndLandCookie.aspx',
        'setLandCookie': '/Services/LotCookie.aspx',
        'setHouseCookie': '/Services/HouseCookie.aspx',
        'setExistingorNewHouseCookie': '/Services/ExistingorNewHouseCookie.aspx'
    };
    //private var
    var slider = {
        init: function () {
            $('#show')
        .before('<div id="paging">')
        .cycle({
            fx: 'scrollHorz',
            speed: '1000',
            timeout: 8000,
            pager: '#paging',
            next: '#slideshow .next',
            prev: '#slideshow .prev'
        });

            //align paging
            var pagingWidth = 480 - ($('#paging').width() / 2);
            $('#paging').css({ 'left': pagingWidth });
        }
    },

    addToCookie = function () {
        $('.housetolotresult.listing').find('.shortList').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "hid=" + $(this).attr("hid") + "&lid=" + $(this).attr("lid");
                if (cthat.is('.active')) {
                    params += "&Action=" + "RemHL";
                    ajaxSaveToCookie(params, servicePoints.setHouseAndLandCookie);
                    //that.parent().find('span input[type="checkbox"]').attr('checked', 'checked');
                }
                else {
                    params += "&Action=" + "AddHL";
                    ajaxSaveToCookie(params, servicePoints.setHouseAndLandCookie);
                }
            });
        });
    },
    removefromhousetolotcookie = function () {
        $('.selectionsummary.favourite').find('.arrowLink').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "hid=" + $(this).attr("hid") + "&lid=" + $(this).attr("lid");
                params += "&Action=" + "RemHL";
                ajaxSaveToCookie(params, servicePoints.setHouseAndLandCookie, $(this).attr("href"));
                e.preventDefault();
                //window.location = $(this).attr("href");
            });
        });
    },

    addToLandCookie = function () {
        $('.lot.listing').find('.shortList').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "lid=" + $(this).attr("data-lotid");
                if (cthat.is('.active')) {
                    params += "&Action=" + "Remove";
                    ajaxSaveToCookie(params, servicePoints.setLandCookie);
                    //that.parent().find('span input[type="checkbox"]').attr('checked', 'checked');
                }
                else {
                    params += "&Action=" + "Add";
                    ajaxSaveToCookie(params, servicePoints.setLandCookie);
                }
            });
        });
    },
    removefromLandCookie = function () {
        $('.lotSummary.favourite').find('.arrowLink').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "lid=" + $(this).attr("data-lotid");
                params += "&Action=" + "Remove";
                ajaxSaveToCookie(params, servicePoints.setLandCookie, $(this).attr("href"));
                e.preventDefault();
                //window.location = $(this).attr("href");
            });
        });
    },

    addToHouseCookie = function () {
        $('.houselist.listing').find('.shortList').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "hid=" + $(this).attr("data-houseid");
                if (cthat.is('.active')) {
                    params += "&Action=" + "Remove";
                    ajaxSaveToCookie(params, servicePoints.setHouseCookie);
                    //that.parent().find('span input[type="checkbox"]').attr('checked', 'checked');
                }
                else {
                    params += "&Action=" + "Add";
                    ajaxSaveToCookie(params, servicePoints.setHouseCookie);
                }
            });
        });
    },

    addToNewOrExistingHouseCookie = function () {
        $('.NeworExistinghouselist.listing').find('.shortList').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "hid=" + $(this).attr("data-houseid");
                if (cthat.is('.active')) {
                    params += "&Action=" + "Remove";
                    ajaxSaveToCookie(params, servicePoints.setExistingorNewHouseCookie);
                    //that.parent().find('span input[type="checkbox"]').attr('checked', 'checked');
                }
                else {
                    params += "&Action=" + "Add";
                    ajaxSaveToCookie(params, servicePoints.setExistingorNewHouseCookie);
                }
            });
        });
    },
    removefromNewOrExistingHouseCookie = function () {
        $('.NewOrExistingHouseSummary.favourite').find('.arrowLink').each(function () {
            $(this).click(function (e) {
                var cthat = $(this);
                var params = "hid=" + $(this).attr("data-houseid");
                params += "&Action=" + "Remove";
                ajaxSaveToCookie(params, servicePoints.setExistingorNewHouseCookie, $(this).attr("href"));
                e.preventDefault();
                //window.location = $(this).attr("href");
            });
        });
    },
    ajaxSaveToCookie = function (params, servicePath, redirectLink) {
        $.ajax({
            type: "POST",
            url: servicePath,
            data: params,
            success: function (text) {
            },
            complete: function () {
                if (redirectLink != undefined)
                    window.location = redirectLink;
            }
        });
    },
	masterNav = function () {

	    $('#nav').find('ul').each(function () {
	        $(this).find('li:first').addClass('first');
	    });

	    var expander = $('#mastHead').find('.expander');
	    expander.click(function (e) {
	        if ($(this).hasClass('active')) {
	            expander.removeClass('active').next('ul').hide();
	            $('body').unbind();
	        } else {
	            expander.addClass('active').next('ul').show();
	            $('body').unbind();
	            $('body').bind('click', function () {
	                expander.removeClass('active').next('ul').hide();
	                $('body').unbind();
	            });
	        }
	        e.stopPropagation();
	    });
	},
    navHover = function () {
        $('#nav').find('li').hover(function () {
            $(this).find('ul').show();
        }, function () {
            $(this).find('ul').hide();
        });

        $('#nav').find('ul li').hover(function () {
            $(this).addClass('hover').next('li').addClass('postHover');
        }, function () {
            $(this).removeClass('hover').next('li').removeClass('postHover');
        });
    },
	showForm = function () {
	    var regForm = $('#banner').find('.registrationForm');
	    //visible = 0;

	    var errorContainer = regForm.find('label.error');
	    var thankyouMessage = regForm.find("li.formSuccess");

	    var hasError = errorContainer.length;
	    var success = thankyouMessage.length;

	    if (hasError || success) {
	        regForm.show();
	    } else {
	        regForm.hide();
	    }
	    var regVisible = 0;

	    $('#banner').find('.registerNow').click(function (e) {
	        if (regVisible == 0) {
	            regVisible = 1;
	            regForm.slideDown(300).show();
	            ga.TrackEvent(null, 'Home_Banner', false, 'Click', 'RegisterNow_Open');
	        } else {
	            regVisible = 0;
	            regForm.slideUp(300, function () {
	                regForm.hide();
	            });
	            ga.TrackEvent(null, 'Home_Banner', false, 'Click', 'RegisterNow_Close');
	        }
	        e.preventDefault();
	    });
	},

    contactForm = function () {
        $('#contactForm').each(function () {
            $(this).find('.expander').click(function () {
                $(this).toggleClass('active').nextAll('ul:first').slideToggle(300);
                return false;
            });
            //this is causing issues.
            //$(this).find('ul > li:even').addClass('clear');
        });


    },
	scrollTo = function (hash) {
	    var target = $(hash);

	    if (target.length) {
	        $('body,html').animate({ scrollTop: target.position().top }, 600);
	    }
	},
    validateBaseForm = function () {
        $("select[id$='ddlTitle']").rules("add", {
            required: true,
            messages: {
                required: "Please select your title."
            }
        });
        $("input[id$='txtPhone']").rules("add", {
            required: true,
            phone: true,
            messages: {
                required: "Please enter your phone number.",
                phone: "The phone number you entered appears to be invalid."
            }
        });
        $("input[id$='txtFirstName']").rules("add", {
            required: true,
            messages: {
                required: "Please enter your first name."
            }
        });
        $("input[id$='txtLastName']").rules("add", {
            required: true,
            messages: {
                required: "Please enter your last name."
            }
        });
        $("input[id$='txtEmail']").rules("add", {
            required: true,
            email: true,
            messages: {
                required: "Please enter your email address.",
                email: "Please enter a valid email address."
            }
        });
        $("select[id$='ddlContactMethod']").rules("add", {
            required: true,
            messages: {
                required: "Please select your preferred contact method."
            }
        });
    };

    // public functions
    return {
        init: function () {
            //            $.ajaxSetup({
            //                cache: false
            //            });

            masterNav();
            navHover();
            addToCookie();
            addToLandCookie();
            removefromLandCookie();
            removefromNewOrExistingHouseCookie();
            removefromhousetolotcookie();
            addToHouseCookie();
            addToNewOrExistingHouseCookie();

            if (window.location.hostname.toLowerCase().indexOf("calderwood") == -1) {
                Cufon.replace('#content .cufon, #cta a, .register h2, h1, .secondary dt, #content h2, #howToFind h3, #content a.title span, #learnMore a', {
                    fontFamily: 'caecilia'
                });
            }
            $('#search').clearOnFocus();
            var hash = window.location.hash;
            if (hash) {
                $('body,html').scrollTop(0);
                scrollTo(hash);
            }

            $('#content .steps').each(function () {
                var parent = $(this);
                parent.find('.question').click(function () {
                    $(this).siblings('.answer').slideToggle(200).parent().toggleClass('active').siblings('.active').removeClass('active').find('.answer').slideUp(200);
                }).parent();
                parent.find('.answer').hide();
            });

            $('#contactForm').each(function () {
                var that = $(this),
                    checker = that.find('.formCheckbox input').eq(1),
                    posts = that.find('.formPostDetails'),
                    checkIt = function () {
                        if (checker.is(':checked')) {
                            posts.slideDown(300);
                        } else {
                            posts.slideUp(300);
                        }
                    };
                checker.change(function () {
                    checkIt();
                });
                checkIt();
            });

            var searchContainer = $('#header .search');

            searchContainer.find('.searchSubmit').remove();
            searchContainer.append('<a href="#" class="searchSubmit">Search</a>');

            var redirectLocation = '/SearchResults.aspx?keywords=';

            $('#header .search a.searchSubmit').click(function (e) {
                e.preventDefault();
                var keywords = jQuery('#header .search input#search').val();
                window.location = redirectLocation + keywords;
            });

            $(".search input[id$='search']").live('keyup', function (e) {
                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 13) {
                    //$(this).siblings($('a.searchSubmit')).trigger('click');
                    var keywords = jQuery(this).val();
                    window.location = redirectLocation + keywords;
                    e.preventDefault();
                }
            });

            var html;
            $(".simple_overlay").overlay({
                expose: '#000',
                onBeforeLoad: function () {
                    $("#youtube-popup").html(html);
                },
                onBeforeClose: function () {
                    $("#youtube-popup").html("");
                }
            });

            $('#content').find('a[rel]').click(function (e) {
                html = $(this).siblings(".videoHolder").html();
                $(".simple_overlay").overlay().load();

                e.preventDefault();
            });

            jQuery('#youtube-popup > a.close').live('click', function () {
                $(".simple_overlay").overlay().close();
                return false;
            });

            var formError = false;
            jQuery("label.error").each(function () {

                var $this = jQuery(this);

                $this.parent().find("label:first span").css("color", "red");
                formError = true;
            });
            if (formError)
                jQuery("span.mandatoryGlobal").css("color", "red");


            $('.tooltipInfo').tooltip({ effect: 'slide' });
        },
        slideshow: function () {
            slider.init();
        },
        form: function () {
            contactForm();
            $('#form1').validate();
            validateBaseForm();
        },
        homeForm: function () {
            showForm();
            $('#form1').validate();
            validateBaseForm();
            //$('#contactForm ul > li:even').addClass('clear');

            var btnSend = $("input[id$='btnSend']");
            var upsell = $("input[id$='hdnUpsell']");
            if (upsell.val() == "1") {
                btnSend.hide();
            }
            else
                btnSend.show();


            var brochureChecked = $("input[id$='cbxBrochure']");
            var register = $("input[id$='cbxReceiveMaterial']");
            var query = $("[id$='txtYourQuery']");
            if (brochureChecked.length > 0 && brochureChecked.is(':visible')) {
                brochureChecked.change(function () {
                    if ($(this).is(':checked'))
                        btnSend.show();
                });
            }

            if (register.length > 0 && register.is(':visible')) {

                register.change(function () {
                    if ($(this).is(':checked'))
                        btnSend.show();
                });
            }

            if (query.length > 0 && query.is(":visible")) {
                query.keypress(function () {
                    if ($(this).val() != '')
                        btnSend.show();
                });

            }
        },
        homeLand: function () {

            $("#content .filter .slide").each(function () {
                var parent = $(this),
                    min = parent.find('.min').hide(),
                    max = parent.find('.max').hide(),
                    slider = $('<div class="slider"/>').appendTo(parent),
                    minTab,
                    maxTab,
                    prefix = parent.data('prefix') || '',
                    affix = parent.data('affix') || '',
                    valMin = parent.data('min') || 0,
                    valMax = parent.data('max') || 100,
                    setMin = parent.data('setmin') || 0,
                    setMax = parent.data('setmax') || 0,
                    sync = function () {
                        var minVal = slider.slider('values', 0),
                        maxVal = slider.slider('values', 1);
                        //Set hidden inputs
                        min.val(minVal);
                        max.val(maxVal);

                        //Set tab val.                        
                        if (slider.parents('dd').hasClass('price')) {
                            minTab.html(minVal / 1000);
                            maxTab.html(maxVal / 1000);
                        } else {
                            minTab.html(minVal);
                            maxTab.html(maxVal);
                        }
                    },
                    stepper = function () {
                        if (slider.parents('dd').hasClass('price')) {
                            var increment = 50000;
                            return increment;
                        }
                    };

                slider.slider({
                    range: true,
                    min: valMin,
                    max: valMax,
                    step: stepper(),
                    values: [setMin, setMax],
                    slide: function () {
                         setTimeout(function(){
                            sync();
                         }, 50);
                    },
                    stop: function () {
                         setTimeout(function(){
                            sync();
                         }, 50);
                    },
                    create: function () {
                        var tabs = slider.find('.ui-slider-handle');

                        //sets min max value of slider
                        minTab = tabs.eq(0).append('<p>' + prefix + '<span>' + slider.slider('values', 0) + '</span>' + affix + '</p>').find('span');
                        maxTab = tabs.eq(1).append('<p>' + prefix + '<span>' + slider.slider('values', 1) + '</span>' + affix + '</p>').find('span');
                        
                        if (slider.parents('dd').hasClass('price')) {
                            parent.append('<p class="min cufon">' + prefix + '<span>' + valMin / 1000 + '</span>' + affix + '</p><p class="max cufon">' + prefix + '<span>' + valMax / 1000 + '</span>' + affix + '</p>');
                        } else {
                            parent.append('<p class="min cufon">' + prefix + '<span>' + valMin + '</span>' + affix + '</p><p class="max cufon">' + prefix + '<span>' + valMax + '</span>' + affix + '</p>');
                        }
                        
                        sync();

                    }
                });
            });

            $('#content .filter .villageList').each(function () {
                var that = $(this),
                    checkAll = that.find('li:first-child').click(function () {
                        if ($(this).is('.active')) {
                            that.find('li').removeClass('active').find('input').removeAttr('checked');
                        } else {
                            that.find('li').addClass('active').find('input').attr('checked', 'checked');
                        }
                    }),
                    checker = that.find('li:gt(0)').click(function (e) {

                        var me = $(this);
                        if (me.is('.active')) {
                            me.find('input').removeAttr('checked');
                            checkAll.removeClass('active').find('input').removeAttr('checked');
                        } else {
                            me.find('input').attr('checked', 'checked');
                            if (checker.length - 1 === checker.filter('.active').length) {
                                checkAll.addClass('active').find('input').attr('checked', 'checked');
                            }
                        }
                        me.toggleClass('active');
                    });

                //not required.. all will be checked by default
                //checkAll.addClass('active').find('input').attr('checked', 'checked');

                that.find(':checked').parent().addClass('active');
                that.find('label').click(function (e) { e.preventDefault(); }).prepend('<span>Click to select</span>').addClass('check');
                that.find('li input').hide();
            });

            Cufon.replace('#selector_blurb h3', {
                fontFamily: 'caecilia'
            });
            //Favourties
            $('#content .favourite').each(function () {
                var that = $(this);
                //load gallery
                that.find('.gallery').vjGallery();

                //setup Cufon
                Cufon.replace(that.find('h3, .cta'), {
                    fontFamily: 'caecilia'
                });

                //slider
                that.children().each(function (i) {
                    var that = $(this),
                        header = that.find('.heading').prepend('<span class="arrow">arrow</span>').click(function () {
                            var that = $(this),
                            headers = that.toggleClass('active').find('h3');

                            Cufon.refresh(headers);
                            that.siblings().slideToggle(300);
                            return false;
                        });

                    if (i === 0) {
                        header.addClass('active');
                    } else {
                        header.siblings().not('.heading').hide();
                    }

                });
            });
            //For List
            $('#content .listing').each(function () {
                var list = $(this),
                    $tooltip = $('<div class="tooltip-validation"><span>Error:</span>You need to select at least one item before you continue to the next step.</div><div class="tooltip-validation bottom"><span>Error:</span>You need to select at least one item before you continue to the next step.</div>'),
                    shortList = list.find('.shortList').click(function (e) {
                        e.preventDefault();
                        var that = $(this);
                        that.toggleClass('active');
                        if (that.is('.active'))
                            that.parent().find('span input[type="checkbox"]').attr('checked', 'checked');
                        else
                            that.parent().find('span input[type="checkbox"]').removeAttr('checked');
                        //return false;
                    }),
                    viewMore = list.find('.view_more'),
                    overlay = $('#home_overlay'),
                    overContent = overlay.find('.content');

                list.find('input[type="checkbox"]').change(function () { $(this).parent().parent().find('a.shortList').toggleClass('active'); }).hide();

                //make validation for next step
                list.siblings('.next_step').click(function () {
                    //console.log('is clicked');
                    if (shortList.filter('.active').length === 0) {
                        //console.log('0 selected');
                        //console.log($tooltip.length + ' tooltips found');
                        $tooltip.stop(true, true).fadeIn(300).delay(5000).fadeOut(200);
                        return false;
                    }
                }).after($tooltip);

                //common functions
                var overlayBinds = function (ind) {
                    var index = ind,
                            overlayList = overContent.find('.shortList').click(function () {
                                overlayList.toggleClass('active');
                                shortList.eq(index).toggleClass('active');
                                return false;
                            }),
                            init = function () {
                                //Finds if it should be set or not
                                if (shortList.eq(index).is('.active')) {
                                    overlayList.addClass('active');
                                }
                                //load gallery
                                overContent.find('.gallery').vjGallery();

                                //setup Cufon
                                Cufon.replace(overContent.find('.cufon, .cta, .main h3'), {
                                    fontFamily: 'caecilia'
                                });
                                
                                $('#home_overlay .tooltipInfo').tooltip({ effect: 'slide' });
                            } ();
                };

                //set overlay load
                //if (!$.browser.msie) {
                    viewMore.each(function () {
                        var that = $(this),
                            ind = that.parent().index(),
                            link = that.attr('href'),
                            escLink = escape(link).replace(/%20/g, '+');
                            
                            

                        that.overlay({
                            expose: '#000',
                            target: '#home_overlay',
                            fixed: false,
                            onBeforeLoad: function () {
                                $('body').addClass('overlay-vis');
                            
                                overContent.hide();
                                $.get(link).success(function(data){
                                    $(data).find('div.favourite').appendTo(overContent);
                                    overContent.slideDown(500, function() {
                                        $('#home_overlay').find('.favourite').css({
                                            display: 'block'
                                        });
                                    });
                                    overlayBinds(ind);
                                    
                                    var script = 'http://s7.addthis.com/js/250/addthis_widget.js?domready=1#pubid=xa-4edc758e06e93d37';
                                    
                                    if (window.addthis){
                                        window.addthis = null;
                                    }
                                    $.getScript(script);
                                    
                                });
                                
                                
                            },
                            onClose: function () {    
                                $('body').removeClass('overlay-vis');
                            
                                overContent.html('');
                                overContent.find('.gallery .list a').unbind('click');
                                overContent.find('.gallery .back').unbind('click');
                                overContent.find('.gallery .next').unbind('click');
                            }
                        });
                    });
                //}
            });
        },
        favourites: function () {
            
        
            $('#content').find('.favouriteHead').click(function (e) {
                var that = $(this);

                if (that.hasClass('active')) {
                    that.removeClass('active');
                    Cufon.refresh();

                    that.next('.favouriteContent').slideUp('fast', function() {
                        $(this).removeAttr('style');
                    });
                } else {
                    that.addClass('active');
                    Cufon.refresh();


                    that.next('.favouriteContent').slideDown('fast', function() {
                        $(this).css({
                            position: 'static'
                        });
                    });
                }
                e.preventDefault();
            });
        }
    };

})();

jQuery.validator.addMethod("phone", function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value.split(' ').join(''));
}, "The phone number you entered appears to be invalid.");

function checkEnter(e) {
    e = e || event;
    return (e.keyCode || event.which || event.charCode || 0) !== 13;
}

/* $ extentions */
jQuery.fn.vjGallery = function () {
    return this.each(function () {
        var that = $(this),
          contain = that.find('.list > ul'),
          list = that.find('.list a'),
          back = that.find('.back'),
          next = that.find('.next'),
          count = list.length,
          current = 0,
          hero = that.find('.heroshot'),
          heroList = '',
          load = function (i) {
              var index = i,
                  container = heroList.hide().eq(i).show();

              if (!container.is('.loaded')) {
                  var url = list.eq(index).attr('href'),
                      img = $('<img />').appendTo(container).hide().bind('load', function () {
                          $(this).fadeIn(500);
                          container.addClass('loaded');
                      }).attr('src', url);
              }
          },
          move = function () {
              var newLeft = current * -95;
              contain.stop(true, true).animate({
                  left: newLeft
              }, 400);
          },
          init = function () {

              //Sets the back and next buttons
              if (count > 6) {
                  //Sets up carousel
                  back.click(function () {
                      if (!back.is('.disable')) {
                          current--;
                          move();
                          if (current === 0) {
                              back.addClass('disable');
                          }
                          next.removeClass('disable');
                      }
                      return false;
                  }).addClass('disable');

                  next.click(function () {
                      if (!next.is('.disable')) {
                          current++;
                          move();

                          if (current >= (count - 6)) {
                              next.addClass('disable');
                          }
                          back.removeClass('disable');
                      }
                      return false;
                  });
              } else {
                  contain.parent().addClass('no-limit');
                  next.hide();
                  back.hide();
              }

              //build the heroshots and appends to the list
              for (i = count; i--; ) {
                  heroList += '<li></li>';
              }
              heroList = $(heroList).appendTo(hero);
              load(0);

              //sets the loaders to display heros
              list.click(function () {
                  var index = $(this).parent().index();
                  load(index);
                  return false;
              });
          } ();
    });
};
  function WebForm_FireDefaultButton(event, target) {
      var __defaultFired = false;
      var __nonMSDOMBrowser =
    window.navigator.appName.toLowerCase()
      if (!__defaultFired && event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
          var defaultButton;
          if (__nonMSDOMBrowser) {
              defaultButton = document.getElementById(target);
          }
          else {
              defaultButton = document.all[target];
          }
          if (defaultButton && typeof (defaultButton.click) != "undefined") {
              __defaultFired = true;
              defaultButton.click();
              event.cancelBubble = true;
              if (event.stopPropagation) event.stopPropagation();
              return false;
          }
      }
      return true;
  }
