/// <reference path="jquery-vsdoc.js" />
function WestingHouse() {
    
    /* START ---> to common/common.js */
    function placeholders() { // 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).val() == 'Enter keywords') $(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);
            });
        });
    }
    
    /* 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();
    }
    //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({
            errorPlacement: function(error, element) {
                $(element).parents('li').prepend(error);
            },
            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: true
        });
        //submitting the form
        $('.validateForm').click(ValidateAndSubmit);
        //Adding phone number validation
        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);
            }
        });
    }

    function fontReplace() {
        Cufon.replace('.cufon', { hover: true });
    }



    /* END ---> to common/common.js */


    function showCarousel() {
        
        if ($('#carousel').length == 0) return;
        $('#slide-show').cycle({
            fx: 'fade',
            speed: 600,
            timeout: 3000,
            pager: '#nav-link'
        });
    }


    /* START ---> to common/common.js */
    /*function comparisonDimensions() {
        if ($(".products").length == 0) return;
        $(".products li").normaliseHeight();
        $(".products li .product").each(function () {
            var product = $(this),
                h = product.height(),
                w = product.width();
            product.css({ top: (145 - h) / 2 + "px", left: (168 - w) / 2 + "px" });
        });
    }*/

    $("a[href^='#']:not(.minimise, .reset)").click(function (e) {
        e.preventDefault();
        var target = $(this).attr("href");
        if (target.length == 1) return;
        $.scrollTo(target, {
            duration: 500
        });
    });

    $(".locator .reset").click(function (e) {
        var $parent = $(this).parents(".wrap");
        $parent.find(":checkbox").attr("checked", false);
        $parent.find(":text").val("");
    });

    $(".print").click(function () {
        window.print();
    });
    /* END ---> to common/common.js */


    var criterias = new Array();

    function facet() {
        if ($('#facet-category').length == 0) return;

        $('#facet-category input').click(function () {
            criterias = new Array();

            $("#facet-category ul").each(function () {
                var criteria = new Object();
                //criteria.name = $(this).data('facet');
                criteria.name = $(this).attr('data-facet');
                var picks = new Array();
                $(this).find('li input:checked').each(function () {
                    picks[picks.length] = $(this).val();
                })
                criteria.value = picks;
                //console.log(criteria.value);
                if (criteria.value.length != 0) {
                    criterias[criterias.length] = criteria;
                }
            })

            if (criterias.length == 0) {
                $('#facet-result li').addClass('show');
                initPagination();
            } else {
                showElementsBaseOnCriterias();
            }
        })
    }


    function showElementsBaseOnCriterias() {
        //console.log(criterias)
        $('#facet-result li').each(function () {
            //console.log($(this));
            $(this).removeClass('hidden show');

            for (var i = 0; i < criterias.length; i++) {
                if (criterias[i].value.length != 0) {

                    if ($(this).attr('data-' + criterias[i].name) == null) {
                        //alert(criterias[i].name + " is null");
                        $(this).addClass('hidden');
                    }
                    else {
                        var value = jQuery.inArray($(this).attr('data-' + criterias[i].name).toString(), criterias[i].value);

                        //alert(criterias[i].name + ' = ' + value + ' = ' + criterias[i].value);
                        if (value == -1) {
                            $(this).addClass('hidden');
                            break;
                        }
                    }
                }
            }
            if ($(this).hasClass('hidden') == false) {
                $(this).addClass('show');
            }
        });
        currentPage = 1;
        initPagination();
    }


    function compare() {
        $('.btn-compare').click(function (e) {
            if ($('.product-buttons :checked').length == 0) return;
        });
        $('.product-buttons input[type=checkbox]').click(function (e) {
            var total = $('.product-buttons :checked').length;
            $('.btn-compare var').text(total);
        });

        var total = $('.product-buttons :checked').length;
        $('.btn-compare var').text(total);
    }

    function tooltips() {
        if ($('.tooltip').length == 0) return;

        $('.tooltip').tooltip({
            bodyHandler: function () {
                return $(this).find('span').html();
            },
            showURL: false,
            track: true,
            fade: 250,
            left: -215
        });
    }

    /* START ---> to common/common.js */
    function rtrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }

    function compareProd() {

        var valstr = rtrim($("#products").val(), '|');
        var guid = $("#guid").val();

        var tokens = valstr.split('|');

        if (tokens == null || tokens.length < 2) {
            alert('Please select two or more products');

        }
        else {
            var q1 = "guid=" + guid;
            var q2 = "&models=" + valstr;
            window.location = "/Compare?" + q1 + q2;
        }
    }
    /* END ---> to common/common.js */


    var currentPage = 1,
        showPerPage = 12,
        firstTimeOpen = true;

    function initPagination(view){
        if($('#facet-result').length === 0) return false;
        //how much items per page to show
        //getting the amount of elements inside content div
        if (firstTimeOpen == true) {
            $('#facet-result li').addClass('show');
        }
        
        var numberOfItems = $('#facet-result li.show').length;

        //calculate the number of pages we are going to have
        var numberOfPages = Math.ceil(numberOfItems / showPerPage);

        //now when we got all we need for the navigation let's make it '

        /*
        what are we going to have in the navigation?
        */
        var navigationHtml = '<li class="copy-red">Page</li>';
        var currentLink = 1;
        while (numberOfPages >= currentLink) {
            navigationHtml += '<li class="number"><a  href="#" longdesc="' + (currentLink) + '">' + (currentLink) + '</a>';
            currentLink++;
        }
        navigationHtml += '<li><a href="#" class="view-all">View all</a></li>';
        navigationHtml += '<li><a class="button btn-compare" href="#" id="btn-compare"><span class="button-inner">Compare selected (<var>0</var>)</span></a></li>';
        
        $('.pagination ul').html(navigationHtml);
        $('.btn-compare').click(function (event) {
            event.preventDefault()
            compareProd();
        });
        
        if(!view) {
            //add active_page class to the first page link
            $('.pagination ul li.number a[longdesc ="1"]').addClass('on');
            //hide all the elements inside content div
            $('#facet-result li').addClass('hidden');
            //and show the first n (show_per_page) elements
            $('#facet-result li.show').slice(0, showPerPage).removeClass('hidden');
        }
        firstTimeOpen = false;
        updateRowEnds();
    };
    
    function removePagination(){ 
        $('.pagination ul li.number a.on').removeClass('on');
        $('.pagination .view-all').addClass('decorate');
    }
    
    function previous() {
        $('.pagination a.previous').click(function (event) {
            event.preventDefault()
            newPage = currentPage  - 1;
            //if there is an item before the current active link run the function
            if ($('li.number a.on').parent().prev('li.number').length != 0) {
                goToPage(newPage);
            }
        });
    }

    function next() {
        $('.pagination a.next').click(function (event) {
            event.preventDefault()
            newPage = currentPage  + 1;
            //if there is an item after the current active link run the function
            if ($('li.number a.on').parent().next('li.number').length != 0) {
                goToPage(newPage);
            }
        });
    }

    function goToPage(pageNum) {
        
        //get the element number where to start the slice from
        startFrom = (pageNum-1) * showPerPage;
        //get the element number where to end the slice
        endOn = startFrom + showPerPage;
        //hide all children elements of content div, get specific items and show them
        $('#facet-result li.show').addClass('hidden').slice(startFrom, endOn).removeClass('hidden');

        /*get the page link that has longdesc attribute of the current page and add active_page class to it
        and remove that class from previously active page link*/
        $('.pagination ul li.number a.on').removeClass('on');
        $('.pagination ul li.number a[longdesc ="'+ pageNum +'"]').addClass('on')
        $('.page_link[longdesc=' + pageNum + ']').addClass('active_page').siblings('.active_page').removeClass('active_page');
        $('.pagination .view-all').removeClass('decorate');
        //update the current page input field
        currentPage = pageNum;
        updateRowEnds()
    }
    
    function showAllProducts() {
        if ($('.view-all').length == 0) return;
        $('body').delegate('.view-all', 'click', function (event) {
            event.preventDefault();
            $("#facet-category input").attr('checked', false);
            $("#facet-result li").removeClass('hidden').addClass('show');
            currentPage = 1;
            initPagination(true);
            removePagination();
        })
    }
    
    function clearAllFacet() {
        if ($('#facet-category').length == 0) return;
        $('a#clear-all').click(function (event) {
            event.preventDefault();
            $("#facet-category input").attr('checked', false);
            $("#facet-result li").removeClass('hidden').addClass('show');
            currentPage = 1;
            initPagination()
        })
    }

    function navigateToPage() {
        $('li.number a').live('click', function (event) {
            event.preventDefault();
            var pageNum = parseInt($(this).attr('longdesc'));
            goToPage(pageNum);
        })
    }

    function updateRowEnds() {
        var $items = $('#facet-result li'),
            $visibleItems = $('#facet-result li:visible'),
            itemCount = 0;
        $items.removeClass('end-row');
        $visibleItems.each(function(i){
            if(itemCount === 3) { itemCount=1; } else { itemCount += 1  }
            if(itemCount === 3) $(this).addClass('end-row');
        });
    }
    
    function showHideMap() {
        if ($('#serviceButton').length == 0) return;
        $('#serviceButton').click(function (e) {
            e.preventDefault();
            $('.span-width-palebox, table.listing, div#map, .locator-text').show();
            $('ul.parts-distributors, div#location-clarification').hide();
            $(this).addClass('active');
             $('#partButton').removeClass('active');
        }).addClass('active');

        $('#partButton').click(function (e) {
            e.preventDefault();
            $('.span-width-palebox, table.listing, div#map, div#location-clarification, .locator-text').hide();
            $('ul.parts-distributors').show();
            $(this).addClass('active');
            $('#serviceButton').removeClass('active');
        })
    }


    /* START ---> to common/common.js */
    function minimiseContent() {
        if ($('a.minimise').length == 0) return;
        var self = this;
        $('a.minimise').click(function (e) {
            e.preventDefault();
            self.toggleView($(this));
        });
        this.toggleView = function(el){
            var $link = el;
            $link.next().slideToggle(500).end().toggleClass('maximise');
            if($link.hasClass('maximise')) $link.html('maximise');
            else $link.html('minimise');
        }
    }

    function fancy() {
        var defaultOpts = {
            'overlayShow': true,
            'padding': 0
        };
        $('.fancy').fancybox(defaultOpts);
    }

    function showHideSerial() {
        if ($('#having-trouble').length == 0) return;

        var imgs = $('#img-holder img');

        $('#serial').change(function (e) {
            e.preventDefault();

            imgs.css('display', 'none');
            $(imgs[$(this).attr('value')]).css('display', 'block');
            $.fancybox.resize();
        });
    }
    
    /* END ---> to common/common.js */

    // Funky product slider
    function cslide(el, options) {
       
        var defaults = {
             transTime: 200,
             waitTime: 0
        };

        this.options = jQuery.extend(defaults, options);

        this.init = function (el) {
            var id = el;
            if (id == '' || !id) return;
            //this.slider = $(id + ' .slides');
            //this.slides = slider.children();
            this.menu = $(id + ' ul li a');
            this.slidebg = $('#slide-bg');
            this.sidePos = this.slidebg.position();
            //this.old = $(this.slides[0]);
            this.flag = true;
            this.events();
        };

        this.events = function () {
            var obj = this;
            $('#product-slide ul li a').live("mouseover mouseout",function(e){
                
                if (e.type == 'mouseover') {
                    if (obj.flag) {
                        var link = $(this);
                        $(this).data('timeout',setTimeout(function() {
                            obj.change(link);         
                        }, obj.options.waitTime));
                    }
                } else {
                    clearTimeout($(this).data('timeout'));
                }
            });
        };
        
        this.change = function (el) {
            var obj = this;
            var index = this.menu.index(el);
            var left = el.position().left;
            this.flag = true; /*false*/

            // imgs of slide
            //this.old.fadeOut(obj.options.transTime); 
            //var current = this.old = $(obj.slides[index]);
            //current.fadeIn(obj.options.transTime);

            // txt of products
            obj.menu.removeClass('active');
            el.addClass('active');
            Cufon.refresh();

            // active slide state
            this.slidebg.animate({
                left: left + this.sidePos.left + 'px'
            }, obj.options.transTime, 'linear', function() {
                obj.flag = true;
            });
        };

        this.init(el);
    }


    function tabBox() {
        var box = $('.facet-wrap');
        if (!box.length) { return; }

        var tabs = box.find('h6');
        var content = box.find('ul').addClass('hidden');
        var firstNode = $(tabs[0]).addClass('active');
        $(content[0]).removeClass('hidden');

        tabs.live('click', function (event) {
            event.preventDefault();
            firstNode.removeClass('active');
            firstNode = $(this).addClass('active');
            content.addClass('hidden');
            $(content[tabs.index(firstNode)]).removeClass('hidden');
        });
    };



    (function init() {
        domFixs(); // exists in global.js
        validateForms();
        placeholders();
        cslide('#product-slide');
        showCarousel();
        fontReplace();
        facet();
        initPagination();
        previous();
        next();
        showAllProducts();
        navigateToPage();
        clearAllFacet();
        minimiseContent();
        //comparisonDimensions();
        compare();
        tooltips();
        fancy();
        $('html').removeClass('no-js');
        showHideMap();
        showHideSerial();
        tabBox();

        $('.register-product-button').bind('click', function () {
            gaEvent('Links', 'Register Product');
        });
    } ());
};



$(function() {
    WestingHouse();
});


// Share widget options
var addthis_config = {
    services_compact: 'facebook, twitter, digg, reddit, tumblr, stumbleupon, email',
    services_exclude: 'print',
    services_expanded : 'facebook, twitter, digg, reddit, tumblr, stumbleupon, delicious, friendster, gmail, live, myspace, orkut, twitthis, wordpress'
}
