/// <reference path="jquery-1.4.2.min.js" />


(function () {
    var validator = {

        pattern: {
            'email': '\\w+@\\w+(\\.\\w+$)+',
            'tel': '^\\d+$'
        },

        method: {
            'data-val-required': function (el, callback) {
                var result;
                if ($(el).is('input:checkbox')) {
                    result = el.attr('checked');
                } else {
                    result = el.val() && el.val().length > 0;
                }
                var errMsg = el.attr('data-val-required');
                if (callback) {
                    callback(el, !!result, errMsg);
                }
                return result;
            },
            'data-val-regex': function (el, callback) {
                var val = el.val();

                if (!val) {
                    return true;
                }

                var pattern = el.attr('data-val-regex-pattern');

                var regStr = validator.pattern[pattern] || pattern;

                var errMsg = el.attr('data-val-regex');

                var reg = new RegExp(regStr);

                var result = reg.test(val);

                if (callback) {
                    callback(el, result, errMsg);
                }
                return result;
            }
        }
    };

    var validatorAPI = {

        registerMethod: function (name, func) {
            validator.method[name] = func;
        },

        registerPattern: function (name, pattern) {
            validator.pattern[name] = pattern;
        }
    };

    // API 
    //    option = {
    //        'valid-selector': '[data-val=true]' , // html attr that decides to valid the field or not 
    //        'elSuccess': function ($el) { // callback on field valid success .
    //        },
    //        'elFailed': function ($el) { // callback on field valid failed .
    //        }
    //    }
    // 
    function valid(option) {

        var config = $.extend({
            'valid-selector': '[data-val=true]',
            'elSuccess': function ($el) {

            },
            'elFailed': function ($el) {

            }
        }, option);

        var inputs = $(config['valid-selector']);

        var fields = [];

        var validQueue = [];

        inputs.each(function () {

            var current = $(this);

            var attr = current.get(0).attributes;

            for (var i = 0; i < attr.length; i++) {
                (function () {
                    var validMethod = validator.method[attr[i].name];
                    if (validMethod != null) {
                        var m = function () {
                            return validMethod(current, function (el, result, errMsg) {
                                var $el = $(el);
                                if (!result) {
                                    $el.data('valid-success', false);
                                    config.elFailed($el, errMsg);
                                } else {
                                    $el.data('valid-success', true);
                                    config.elSuccess($el);
                                }
                            });
                        };
                        validQueue.push(m);
                        current.blur(m);
                    }
                })();
            }
        });

        var cansubmit = function () {
            var r = true;
            for (var i = 0; i < validQueue.length; i++) {
                var tempResult = (!!validQueue[i]());
                r = tempResult && r;
            }
            return r;
        };

        var validResult = {
            result: cansubmit(),
            cansubmit: cansubmit,
            fields: []
        };

        return validResult;
    }

    window.valid = valid;
    valid.validatorAPI = validatorAPI;
})();

(function fixed() {
    window.breadcrumb = {};

    /// show current menu
    $(function () {
        // fixed current menu
        var breadcrumbPath = [];
        for (var p in window.breadcrumb) {
            breadcrumbPath.push(window.breadcrumb[p].toLocaleLowerCase());
        }

        $('#left-sidebar div.menu li a').each(function () {
            var inArray = $.inArray($(this).attr('href').toLocaleLowerCase(), breadcrumbPath);
            //alert(inArray);
            if (inArray > 0) {
                $(this).addClass('current');
            }
        });
    });
})();

$(function () {

    //#region window resize
    (function handleResize() {
        function heightResize() {
            var leftHeight = 0;
            for (i = 0; i < $('#left-sidebar').children().size(); i++) {
                leftHeight += $('#left-sidebar').children().eq(i).outerHeight();
            }
            var mainHeight = 20;
            for (i = 0; i < $('#main').children().size(); i++) {
                mainHeight += $('#main').children().eq(i).outerHeight();
            }
            maxHeight = Math.max($(window).height(), Math.max(leftHeight, mainHeight));
            if (maxHeight == mainHeight) {
                maxHeight += 40;
            }
            $('#left-sidebar').height(maxHeight - 30);
            $('#right-sidebar').height(maxHeight);
            $('#main').height(maxHeight - 20);

        }
        //List resize
        function listResize() {
            liWidth = $('.list li').width();
            listWidth = $('.list').width();
            listNumber = Math.floor((listWidth + 26) / (liWidth + 26));
            $('.list li.last').removeClass('last');
            for (i = 0; i < $('.list li').size(); i++) {
                if ((i + 1) % listNumber == 0) {
                    $('.list li').eq(i).addClass('last');
                }
            }
        }

        //List resize
        setTimeout(function () {
            listResize();
        }, 10);
        //Height resize
        heightResize();
        //Background height
        $('#background').height(Math.max($(document).height(), $(window).height()));

        $(window).resize(function () {
            listResize();
            heightResize();
            $('#background').height(Math.max($(document).height(), $(window).height()));

            var mapWidth = $('.content').width();
            $('#directionsPanel').width(mapWidth);
            $('#map_canvas').width(mapWidth);

            
        });

        //Menu
        $('.menu a').hover(function () {
            $(this).parent().siblings('li').removeClass('hover');
            $(this).parent().addClass('hover');
        });
        $('.menu').mouseout(function () {
            $(this).find('li').removeClass('hover');
        });
    })();
    //#endregion


    //#region change background 

    (function handleBackgrounChange() {
        var seed = 0, changeCount = 0;

        var backgroundImg = $("#backgrounImg");

        backgroundImg.load(function () {
            backgroundImg.fadeIn();
        });

        var backgroundInfo = $("#BackgroundInfo");

        var swicherLiList = $('#background-switcher li').each(function (index) {
            $(this).click(function () {
                changeBackground(index);
            });
        });

        var count = swicherLiList.length || 1;

        var randomSeed = parseInt(Math.random() * 1000000000) % count;

        changeBackground(randomSeed);

        function changeBackground(index) {

            seed = index;
            swicherLiList.removeClass('active');
            var current = swicherLiList.filter(':eq(' + index + ')');
            current.addClass('active');

            //change info image 
            var currentInfoImg = current.find('img.info');


            //change background image
            var currentBackImg = current.find('img.large');

            if (changeCount > 0) {
                backgroundInfo.find('img').fadeOut('slow', function () {
                    $(this).attr('src', currentInfoImg.attr('src')).fadeIn('slow');
                });
                backgroundImg.fadeOut('slow', function () {
                    $(this).attr('src', currentBackImg.attr('src')).fadeIn('slow');
                });

            } else {
                backgroundInfo.find('img').attr('src', currentInfoImg.attr('src'));
                backgroundImg.attr('src', currentBackImg.attr('src'));
            }


            changeCount++;
        }

        setInterval(function () {
            seed++;
            changeBackground(seed % count);
        }, 5000); //change background every 5 seconds

    })();

    //#endregion

    (function fixed() {
        // bread crumb 
        $('ul.breadcrumb li:last').remove();
        var txt = $('ul.breadcrumb li').last().text();
        $('ul.breadcrumb li').last().html(txt);
    })();
});

