/// <reference path="jquery-vsdoc.js" />
//<body data-controller="forms" data-action="validate">
//Will call ORCHARD.SITE.common.init() ORCHARD.SITE.forms.init() and ORCHARD.SITE.forms.validate()
var ORCHARD = ORCHARD || {};

ORCHARD.SITE = {
    common: {
        init: function() {
            // application-wide code
            $('html').removeClass('no-js');
            this.navslide();
            this.headerAction();
            if($('.slideshow').length !== 0) ORCHARD.SITE.slideShow.init();
        },
        navslide: function() {
            var $navigation = $('.navigation'),
                $item = $navigation.find('li').has('ul').find('a:eq(0)'),
                browser = $('html').attr('class');
            if($item.parent().hasClass('current')){
                $item.append('<img class="less" src="/common/images/icon.less.gif" alt="less" />');
            }
            else {
                $item.append('<img class="more" src="/common/images/icon.more.gif" alt="more" />');
            }
            $navigation.find('img').bind('click', function(event) {
                event.preventDefault();
                slide(event.target);
            });
            function slide(el){
                var $target = $(el),
                    state = $target.attr('class');
                if(state == 'more'){
                    $target.attr({ 'src': '/common/images/icon.less.gif', 'class': 'less', 'alt': 'less'});
                    if(browser == 'ie6' || browser == 'ie7') { $target.parent().next().show(); } else { $target.parent().next().slideDown(); }
                }
                else {
                    $target.attr({ 'src': '/common/images/icon.more.gif', 'class': 'more', 'alt': 'more'});
                    if(browser == 'ie6' || browser == 'ie7') { $target.parent().next().hide(); } else { $target.parent().next().slideUp(); }
                }
            }
        },
        headerAction: function() {
            if($('#header-action').length === 0) return false;
            $('#header-action').bind('click', function(event) {
                event.preventDefault();
                slideAction(event.target);
            });
            function slideAction(el){
                var $target = $(el),
                    $actionTab = $('#header-action-tab'),
                    state = $('#header-action').attr('data-action')
                if(state == 'show') {
                    $actionTab.slideDown();
                    $target.attr({ 'data-action': 'hide', 'class': 'hide'});
                }
                else {
                    $actionTab.slideUp();
                    $target.attr({ 'data-action': 'show', 'class': 'show'});
                }
            }
        }
    },
    forms: {
        init: function() {
            // controller-wide code
            this.placeholders();
        },
        placeholders: function() {
            // Replacing placehlder attributes in browsers that don't support them
            // Adapted from http://www.beyondstandards.com/archives/input-placeholders/
            var supported = !!("placeholder" in document.createElement( "input" ));
            if (supported) return;
            $('input[placeholder]').each(function() {
                var placeholder = $(this).attr('placeholder');
                if ($(this).val() == '') $(this).addClass('placeholder').val(placeholder)
                $(this).focus(function() {
                    if ($(this).val() == placeholder) $(this).removeClass('placeholder').val('');
                    return false;
                }).blur(function() {
                    if ($(this).val() == '') $(this).addClass('placeholder').val(placeholder);
                });
            });
        },
        validate: function() {
            // Validation code
            /* Validation for forms*/
            function ValidateAndSubmit(evt) {
                var $group = $(evt.currentTarget).parents('fieldset');
                var isValid = true;
                $group.find(':input').each(function (i, item) {
                    if (!$(item).valid())
                        isValid = false;
                });
                if (!isValid) {
                    evt.preventDefault(); 
                } else {
                    //IF I'M POSTED FROM THE HEADER FORM POST VIA AJAX TO THE HANDLER
                    if($(evt.target).parents('div#header-action-tab').length === 1) {
                        var $formContainer = $(evt.target).parents('div#header-action-tab'),
                            firstName = $formContainer.find('input.first-name').val(),
                            lastName = $formContainer.find('input.last-name').val(),
                            emailAddress = $formContainer.find('input.email-address').val(),
                            contactNumber = $formContainer.find('input.contact-number').val(),
                            companyName = $formContainer.find('input.company-name').val(),
                            containerHeight = $formContainer.outerHeight(),
                            containerWidth = $formContainer.outerWidth();
                        evt.preventDefault();
                        $formContainer.append('<div class="loader"></div>');
                        if($('html').hasClass('ie6')) $formContainer.find('.loader').css({ 'height': containerHeight, 'width': containerWidth });
                        $.post("/Common/Handlers/BookDemoHandler.ashx", { first_name: firstName, last_name: lastName, email_address: emailAddress, contact_number: contactNumber, company_name: companyName },
                           function(data){
                             var returnMessages = {
                                success: "Thanks. We'll be in touch soon.",
                                fail: "Sorry, There was an error when handling your demo request. Please contact us using the details below."
                                },
                                response = data;
                            $formContainer.find('fieldset').remove();
                            $formContainer.find('.loader').remove();
                             if(response == 'true') {
                                $formContainer.append($('<h3>' + returnMessages.success + '</h3>'));
                             } else { 
                                $formContainer.append($('<h3>' + returnMessages.fail + '</h3>'));
                                $formContainer.find('.validateForm').attr('disabled', 'false');
                             }
                           });
                    }
                }
            }
            //adding a method for phone number validation
            jQuery.validator.addMethod("validPhoneNumber", function (value, element, param) {
                var $p = $(element).parent();
                var reg = /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$/;
                if (value.match(reg) != null) {
                    $p.removeClass('error');
                    $p.find('label.error').remove();
                    $(element).removeClass('error');
                    return true;
                }
                $p.addClass('error');
                return false;
                },
                jQuery.validator.format("Please enter a valid phone number")       
            );
            //adding a method for Australian date validation
            jQuery.validator.addMethod("dateAU", function (value, element) {
                var check = false;
                var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
                if( re.test(value)){
                    var adata = value.split('/');
                    var gg = parseInt(adata[0],10);
                    var mm = parseInt(adata[1],10);
                    var aaaa = parseInt(adata[2],10);
                    var xdata = new Date(aaaa,mm-1,gg);
                    if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
                        check = true;
                    else
                        check = false;
                } else
                    check = false;
                return this.optional(element) || check;
            }, 
            "Please enter a correct date in the format DD/MM/YYYY"
            );
            //adding a method for postcode validation
            jQuery.validator.addMethod("validPostcode", function (value, element, param) {
                var $p = $(element).parent();
                if(value.length == 0) return true;
                var reg = /^\d{4}$/;
                if (value.match(reg) != null) {
                    $p.removeClass('error');
                    $p.find('label.error').remove();
                    $(element).removeClass('error');
                    return true;
                }
                $p.addClass('error');
                return false;
            },
                jQuery.validator.format("Please enter a valid postcode 4 digits in length")
            );
            //setting the options for form validation
            function validateForms() { 
                //validation options
                $("#aspnetForm").validate({
                    highlight: function(element, errorClass) {
                        $(element).parents('li').addClass(errorClass);
                    },
                    unhighlight: function(element, errorClass) {
                        $(element).parents('li').removeClass(errorClass);
                    },
                    onsubmit: false,
                    onkeyup: false,
                    focusInvalid: true,
                    ignoreTitle: false
                });
                //submitting the form
                $('.validateForm').click(ValidateAndSubmit);
                //Adding phone number validation
                if ($(".validPostcode").length != 0) $(".validPostcode").rules("add", { validPostcode: true });
                if ($(".validPhoneNumber").length != 0) $(".validPhoneNumber").rules("add", { validPhoneNumber: true });
    
                //dealing with the enter button
                $('fieldset :text').keydown(function (evt) {
                    if (evt.keyCode == 13) {
                        ValidateAndSubmit(evt);
                    }
                });		
            }
            validateForms();
        }
    },
    slideShow: {
        constants: { 
            $SLIDE_SHOW: $('.slideshow'),
            $SLIDE_PAGES: 0,
            NUMBER_OF_SLIDES: 0,
            CURRENT_SLIDE: 1
        },
        init: function() {
            console.log('start the show');
            this.constants.NUMBER_OF_SLIDES = this.constants.$SLIDE_SHOW.find('.slide').length;
            this.constants.$SLIDE_SHOW.find('.slide').not('.slide:eq(0)').hide();
            this.createControls();
            this.autoScroll();
        },
        autoScroll: function() {
            timeoutID = setInterval(function() {
                    ORCHARD.SITE.slideShow.showNextSlide(ORCHARD.SITE.slideShow.constants.$SLIDE_SHOW.find('.slide-next a'));
            }, 5000);
        },
        createControls: function() {
            var $controlNext = $('<li class="slide-control slide-next"><a href="#">next</a></li>'),
                $controlPrev = $('<li class="slide-control slide-prev"><a href="#">prev</a></li>'),
                $pages = $('<li class="slide-pages">' + this.constants.CURRENT_SLIDE + '/' + this.constants.NUMBER_OF_SLIDES + '</li>');
            this.constants.$SLIDE_SHOW.append($controlNext);
            this.constants.$SLIDE_SHOW.prepend($controlPrev);
            this.constants.$SLIDE_SHOW.append($pages);
            this.constants.$SLIDE_PAGES = $pages;
            $controlPrev.find('a').bind('click', function(event) {
                event.preventDefault();
                window.clearInterval(timeoutID);
                ORCHARD.SITE.slideShow.showNextSlide(event.target);
            });
            $controlNext.find('a').bind('click', function(event) {
                event.preventDefault();
                window.clearInterval(timeoutID);
                ORCHARD.SITE.slideShow.showNextSlide(event.target);
            });
        },
        showNextSlide: function(el) {            
            var $slides = this.constants.$SLIDE_SHOW.find('.slide'),
                current = this.constants.CURRENT_SLIDE,
                total = this.constants.NUMBER_OF_SLIDES,
                next = 0;
            if($(el).parent().hasClass('slide-next')){
                if(current === total) { next = 1 } else { next = current + 1; }
            } else {
                if(current === 1) { next = total } else { next = current - 1; }
            }
            //set default
            this.constants.CURRENT_SLIDE = next;
            this.constants.$SLIDE_SHOW.find('.slide-control a').hide();
            $slides.eq(current - 1).fadeOut(400, function() {
                $slides.eq(next - 1).fadeIn(400);
                ORCHARD.SITE.slideShow.constants.$SLIDE_SHOW.find('.slide-control a').show();
            });
            this.updatePages();
        },
        updatePages: function() {
            this.constants.$SLIDE_PAGES.html(this.constants.CURRENT_SLIDE + '/' + this.constants.NUMBER_OF_SLIDES);
        }
    }
};


ORCHARD.UTIL = {
  exec: function( controller, action ) {
    var ns = ORCHARD.SITE,
        action = ( action === undefined ) ? "init" : action;
    if ( controller !== "" && ns[controller] && typeof ns[controller][action] == "function" ) {
      ns[controller][action]();
    }
  },

  init: function() {
    var body = document.body,
        controller = body.getAttribute( "data-controller" ),
        action = body.getAttribute( "data-action" );
    ORCHARD.UTIL.exec( "common" );
    ORCHARD.UTIL.exec( controller );
    ORCHARD.UTIL.exec( controller, action );
  }
};

$(document).ready(function() {
    ORCHARD.UTIL.init();
});
