/** 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 () {

    //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 });
        }
    },
	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');
        }, function () {
            $(this).removeClass('hover');
        });
    },
	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();
            Cufon.replace('#cta a, h1, h3, h4, #content h2, #howToFind h3, #content a.title span, #content .cufon, #learnMore a', {
                fontFamily: 'Baskerville Old Face'
            });
			
			 Cufon.replace('#nav li a span, .register h2, #content dt:not(#content dt.callOut)', {
                fontFamily: 'Avenir LT Std'
            });
			
            $('#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");
        },
        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.
                        minTab.html(minVal);
                        maxTab.html(maxVal);


                        //makes the 
                    };

                slider.slider({
                    range: true,
                    min: valMin,
                    max: valMax,
                    values: [setMin, setMax],
                    slide: function () {
                        sync();
                    },
                    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');
                        parent.append('<p class="min">' + prefix + '<span>' + valMin + '</span>' + affix + '</p><p class="max">' + prefix + '<span>' + valMax + '</span>' + affix + '</p>');
                        sync();

                    }
                });
            });
            $('#content .filter .villageList').each(function () {
                var that = $(this),
                    all = $('<li><label><span>Decal</span> Select All</label></li>').prependTo(that.find('ul')).find('label').click(function () {
                        if ($(this).is('.active')) {
                            that.find('label').removeClass('active').find('input').removeAttr('checked');
                        } else {
                            that.find('label').addClass('active').find('input').attr('checked', 'checked');
                        }

                    }),
                    checker = that.find('input:checkbox').click(function () {
                        var parent = $(this).parent().toggleClass('active');
                        if (parent.is('.active')) {
                            if (checker.length === checker.filter(':checked').length) {
                                all.addClass('active');
                            }
                        } else {
                            all.removeClass('active');
                        }
                    });
                checker.filter(':checked').parent().addClass('active');
                checker.parent().append('<span>Decal</span>').addClass('check');
            });
            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),
                    shortList = list.find('.shortList').click(function () {
                        var that = $(this);
                        that.toggleClass('active');
                        return false;
                    }),
                    viewMore = list.find('.view_more'),
                    overlay = $('#home_overlay'),
                    overContent = overlay.find('.content');

                //make validation for next step
                list.siblings('.next_step').click(function () {
                    if (shortList.filter('.active').length === 0) {
                        $(this).find('.tooltip').stop(true, true).fadeIn(300).delay(5000).fadeOut(200);
                        return false;
                    }
                }).append('<div class="tooltip"><span>Error:</span>You need to select at least one item before you continue to the next step.</div>');

                //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('h3, .cta'), {
                                    fontFamily: 'caecilia'
                                });
                            } ();
                };

                //set overlay load
                viewMore.each(function () {
                    var that = $(this),
                        ind = that.parent().index(),
                        link = that.attr('href');

                    that.overlay({
                        expose: '#000',
                        target: '#home_overlay',
                        fixed: false,
                        onBeforeLoad: function () {
                            overContent.hide().load(link, function () {
                                overContent.slideDown(500);
                                overlayBinds(ind);
                            });
                        },
                        onClose: function () {
                            overContent.html('');
                            overContent.find('.gallery .list a').unbind('click');
                            overContent.find('.gallery .back').unbind('click');
                            overContent.find('.gallery .next').unbind('click');
                        }
                    });
                });
            });
        }
    };

})();

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;
}
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;
}
