var MMG = (function () {

    var overlay = {
        that: this,
        content: '',
        bg: '',
        loader: function (type, url, pos) {
            var ind = pos || -1;
            if (ind < 0) {
                ind = 0;
                //console.log('turned to 0');
            }

            this.content.addClass(type);
            if (type === 'gallery') {
                //load in gallery
                $.get(url, function (data) {
                    if (data) {
                        overlay.content.addClass('loaded').html(data);
                        overlay.open();
                        overlay.initGallery(ind);
                    }
                });
            } else if (type === 'video') {
                overlay.open();
                overlay.initVideo(url);
            }
        },
        open: function () {
            this.content.fadeIn(400);
            overlay.bg.fadeIn(400);
            return false;
        },
        close: function () {

            //remove events and binds
            if (this.content.hasClass('gallery')) {
                this.content.find('.gallery ul').cycle('destroy');
            };
            if (this.content.hasClass('video')) {
                swfobject.removeSWF('video');
            };

            $('html').unbind('keyup');

            overlay.content.fadeOut(200, function () {
                overlay.content.removeClass().html('');
            });
            this.bg.fadeOut(200);
            return false;
        },
        initGallery: function (pos) {
            //console.log(pos);
            var cycler = jQuery('#overlay .gallery ul'),
                ind = pos;
            //Set up cycle
            cycler.cycle({
                fx: 'scrollHorz',
                speed: 500,
                next: jQuery('#overlay .gallery .next'),
                prev: jQuery('#overlay .gallery .back'),
                pager: overlay.content.find('.controls .nav'),
                before: function (slide, next, options, forwardFlag) {
                    jQuery(next).find('p, a').hide();
                    jQuery(slide).find('p, a').fadeOut(200);
                },
                after: function (slide, next, options, forwardFlag) {
                    jQuery(next).find('p, a').fadeIn(200);
                },
                startingSlide: ind
            });

            //Setting up keys
            $('html').keyup(function (e) {
                var key = e.keyCode;
                switch (key) {
                    case 37:
                        cycler.cycle('prev');
                        break;
                    case 39:
                        cycler.cycle('next');
                        break;
                    case 27:
                        overlay.close();
                        break;
                    default:
                }
            });
        },
        initVideo: function (videoUrl) {
            overlay.content.append('<div id="video"><p>' + needFlash + '</p></div><div class="controls"><a class="close" href="#">' + closeText + '</a></div>');

            //Flash video params :S
            var params = {
                allowScriptAccess: "sameDomain",
                allowFullScreen: "true",
                menu: "false",
                base: "/includes/flash/"
            };
            var styles = {
                url: videoUrl, 		// The URL to the video
                autoPlay: true, 			// [Optional] Default: false	- Determines if the video will begin automatically playing (if true, the preview image will NOT be loaded)
                autoHideControls: true, 		// [Optional] Default: true		- Determines if the controls are automatically hidden when the mouse leaves the player, or is still for several seconds
                colorForeground: "#ffffff", 	// [Optional] Default: #FFFFFF	- The foreground color of interface elements
                colorBackground: "#ffffff", 	// [Optional] Default: #222222	- The background color of interface elements
                colorTheme: "#c10926", 		// [Optional] Default: #FFCC00	- The theme color of interface elements
                controls: "scrub,time,duration,volume,fullscreen", // [Optional] Default: scrub,time,duration,volume,fullscreen	- The controls that are shown. Available options: scrub, time, duration, volume, quality, fullscreen
                framing: "touchinside", 		// [Optional] Default: touchinside - The framing of the video. Available options: normal, stretch, touchinside, touchoutside
                volume: 0, 					// [Optional] Default: 1		- The initial volume of the video
                bufferPerc: 0.1, 			// [Optional] Default: 0.1		- The percentage of the video to buffer before it will begin playing (between 0 and 1. If bufferTime is set to a value > 0, this value is NOT used)
                bufferTime: 0,
                showSpinner: true
            };
            swfobject.embedSWF("/includes/flash/vjvideoplayer.swf", "video", "608", "428", "9.0.260.0", false, styles, params, { id: "video", name: "video" });

            //Setting up keys
            $('html').keyup(function (e) {
                if (e.keyCode === 27) {
                    overlay.close();
                };
            });
        },
        init: function () {
            $('#container').after('<div id="overlay"></div><a href="#" id="overlay_background">' + closeText + '</a>');
            overlay.content = $('#overlay');
            overlay.bg = $('#overlay_background').click(function () {
                overlay.close();
                return false;
            });
            //Live event for close button.
            overlay.content.find('.close').live('click', function () {
                overlay.close();
            });

            //Find all the overlay popup elements
            $('#content .overlay-gallery, #content .overlay-video, #primary .overlay-album').click(function () {
                var that = $(this),
                    type = that.hasClass('overlay-video') ? 'video' : 'gallery',
                    url = that.attr('rel'),
                    pos = -1;

                if (that.is('.overlay-album')) {
                    pos = that.parent().index();
                    //console.log('first: ' + pos);
                };
                if (type && url) {
                    overlay.loader(type, url, pos);
                }
            });
        }
    },
    closeText = 'close',
    needFlash = 'You need to install Flash player to view this video. <a href="http://get.adobe.com/flashplayer" target="_blank">Click here</a> to download it.',
    clearOnFocus = function (ele, val) {
        var that = $(ele),
            eleVal = val || '',
            rel = that.attr('rel');
            
        if(rel && !eleVal){
            eleVal = rel;
        }
        
        that.val(eleVal);

        if (that.length) {
            that.focus(function () {
                var that = $(this);
                if (that.val() === eleVal) {
                    that.val('');
                }
            }).blur(function () {
                var that = $(this);
                if (that.val() === '') {
                    that.val(eleVal);
                }
            });
        }

    },
    sitecore = function (selector) {
        //This is why nobody likes sitecore.
        var selec = selector,
                lawlSitecore = WebForm_DoPostBackWithOptions,
                lawlSitecore2 = ValidatorUpdateDisplay;

        WebForm_DoPostBackWithOptions = function (p1, p2, p3, p4, p5, p5, p6) {
            lawlSitecore(p1, p2, p3, p4, p5, p5, p6);
            jQuery(selec).removeClass('error').children('span:visible').parent().addClass('error');
        }
        ValidatorUpdateDisplay = function (val) {
            lawlSitecore2(val);
            jQuery(selec).removeClass('error').children('span:visible').parent().addClass('error');
        };
        jQuery(selec).removeClass('error').children('span:visible').parent().addClass('error');
    },
    dropDown = function (ele) {
        var dropdowns = $(ele).each(function () {
            var that = $(this),
                dropdown = $('<div class="dropdown"><a href="#"><em></em><span>Drop down arrow</span></a><ul></ul></div>'),
                options = '',
                selected = that.find('option:selected').index() || 0;

            //grab options
            that.find('option').each(function (i) {
                var val = $(this).html();

                //if it's first than we set it as active
                if (i === selected) {
                    dropdown.find('em').html(val);
                }
                else {
                    options += '<li><a href="#">' + val + '</a></li>';
                }
            });

            //pushes options into dropdown
            dropdown.find('ul').append(options);
            dropdown.vjDropdown(true);

            //hide select show dropdown
            that.hide().before(dropdown);
        });

        return dropdowns;
    };

    return {
        init: function () {
            var bodz = $('body');
            if (bodz.hasClass('english')) {
                Cufon.replace('.cufon, #footer .sitemap h3', { fontFamily: 'Chevin' });
                Cufon.replace('#header .navigation > li > a', { fontFamily: 'Chevin', hover: true });
            } else {
                $('html').addClass('cufon-active');
            }
            
            if(bodz.is('.zh-tw')){
                closeText = '關閉';
                needFlash = '您需要安装Flash Player才能观看此录像，<a href="http://get.adobe.com/flashplayer" target="_blank">点击这里下载。</a>'
            } else if (bodz.is('.zh-cn')){
                closeText = '关闭';
                needFlash = '您需要安裝Flash Player才能觀看此錄像，<a href="http://get.adobe.com/flashplayer" target="_blank">點擊這裏下載。</a>'
            }
                
            if (!swfobject.hasFlashPlayerVersion("10")) {
                $('#flash').css('visibility','visible');
                var today = new Date();
                today.setTime(today.getTime());

                var expires = new Date(today.getTime() + (7 * 1000 * 60 * 60 * 24)); // 7 days
                document.cookie = "NoFlash=1;expires=" + expires.toGMTString();
            }

            overlay.init();

            //Search clear on focus
            clearOnFocus('#header .search input[type=text]');
            //clearOnFocus('#primary .search input[type=text]');

            $('#secondary dl dd:has(ul) a').click(function () {
                $(this).parent().toggleClass('active').find('ul').toggle(300);
                return false;
            });

            $('#content .per_page, #content .dropdown').vjDropdown();

            $('#content .tabs').each(function () {
                var that = jQuery(this),
                    nav = that.find('.nav > li'),
                    content = jQuery('<div class="content" />');

                nav.each(function (index) {
                    jQuery(this).children('div').appendTo(content);
                });
                that.append(content);
                content = content.children('div');
                content.hide().first().show();
                nav.find('a').click(function () {
                    var ind = 0,
                        parent = $(this).parent();

                    if (parent.hasClass('active')) {
                        return false;
                    }

                    nav.removeClass('active');
                    ind = parent.addClass('active').index();
                    content.slideUp(200).eq(ind).slideDown(200);
                    return false;
                }).first().parent().addClass('active');
            });

            $('#content .filters').each(function () {
                var parent = $(this),
                    filter = parent.find('.filter_selection'),
                    decal = filter.find('.decal'),
                    checkboxes = filter.find('input:checkbox');

                parent.find('.filter').click(function () {
                    $(this).toggleClass('active');
                    filter.slideToggle(200);
                    return false;
                });

                filter.find('.close').click(function () {
                    filter.slideUp(200);
                    parent.find('.filter').removeClass('active');
                    return false;
                });

                checkboxes.click(function () {
                    var that = $(this),
                        check = false,
                        parent = that.is('.show_all') ? that.parent().parent().parent() : that.parent().parent(),
                        showAll = filter.find('.show_all');

                    if (that.attr('checked')) {
                        check = true;
                    }

                    //if it's just a normal input
                    if (!that.is('.show_all') && !that.is('.show_section')) {
                        if (!check) {
                            parent.find('.show_section').attr('checked', false);
                            showAll.attr('checked', false);
                        }
                    } else {
                        parent.find('input:checkbox').attr('checked', check);
                        if (!that.is('.show_all') && !check) {
                            showAll.attr('checked', false);
                        }
                    }
                });
                
                    //checks to see if show all is checked
                    if(checkboxes.filter('.show_all').attr('checked')){
                        checkboxes.attr('checked', true);
                    }
            });
            //Replaces Select with custom dropdown
            dropDown('#content select');

            $('#content .contact fieldset').each(function () {
                var that = $(this),
                    select = that.find('select'),
                    submit = that.find('input[type=submit]');

                //gets span decal to behave on hover events    
                submit.hover(function () {
                    $(this).parent().addClass('active');
                }, function () {
                    $(this).parent().removeClass('active');
                }).focus(function () {
                    $(this).parent().addClass('active');
                }).blur(function () {
                    $(this).parent().removeClass('active');
                });
            });

            $('#faq').each(function () {
                var that = $(this),
                    answer = that.find('.answer'),
                    questions = that.find('.question');

                answer.hide().first().show();
                questions.first().addClass('expanded');

                that.find('.open').click(function () {
                    var that = $(this);
                    if(that.is('.active')){
                        questions.removeClass('expanded');
                        answer.slideUp(300);
                        that.removeClass('active').html('Open all');
                    } else {
                        questions.addClass('expanded');
                        answer.slideDown(300);
                        that.addClass('active').html('Close all');
                    }
                    return false;
                });

                questions.click(function () {
                    $(this).toggleClass('expanded');
                    $(this).siblings('.answer').slideToggle(300);
                    return false;
                });
                Cufon.replace('#faq .title');
            });

            $('#news_actions .print_page a').click(function () {
                window.print();
                return false;
            });
            //rating
            $('#content .was_this_useful').each(function () {
                var that = jQuery(this);

                var choices = that.find('a').click(function () {
                    $(this).parent().find('.feedback').slideDown(300);
                    $(this).addClass('active').siblings('a').removeClass('active');
                    return false;
                });

                var pagerating = that.find(".pagerating").click(function (e) {
                    if (!(jQuery(".error").is(":visible"))) {
                        var choice = choices.filter('.active').html(),
                            comment = jQuery(".txtComments").val();
                        ajaxSaveData(choice, comment, window.location);
                        e.preventDefault();
                    }
                });

                var ajaxSaveData = function (option, comment) {
                    var param = "option=" + option + "&comment=" + comment + "&pageUrl=" + document.location.href;
                    //alert(param);
                    jQuery.ajax({
                        type: "POST",
                        url: "/Services/Rating.aspx",
                        data: param,
                        success: function (text) {
                            var html = '<p class="thankyou">' + text + '</p>';
                            choices.unbind('click');
                            pagerating.unbind('click');
                            that.fadeOut(200, function () {
                                that.html(html).fadeIn(200);
                            });
                        },
                        // Rebind data and set pageno textbox.
                        complete: function () {
                        }
                    });
                };

                sitecore('#primary .feedback');
            });

            $(".aside > li:last").addClass("last");
            
            $('#header .map').hover(function(){
                $(this).addClass('active');
            }, function(){
                $(this).removeClass('active');
            }).click(function(){
                var link = $(this).find('a').attr('href') || '#';
                window.location = link;
                return false;
            });
            
            $('#content .maps').masonry({
                columnWidth: 473,
                gutterWidth:15,
                itemSelector: 'li'
            });
            
            //IE SUCKS
            if(browserName=navigator.appName === "Microsoft Internet Explorer"){
                $('#content table').wrap('<fieldset class="table" />');
            } else {
                $('#content table').wrap('<div class="table" />');
            }
            
            $('#content .companycode').each(function(){
                var companyCode = $(this).text();
                    companyCode = companyCode.replace('(', '<br />(');
                $(this).html(companyCode);
            });

        },
        nav: function(){
            //Navigation dropdown
            var nav = $('#header .navigation > li'),
            secondNav = nav.children('ul');

            nav.hover(function () {
                var that = $(this);
                that.addClass('hover').find('ul').slideDown(200);
                if (that.is('.active')) {
                    Cufon.refresh('#header .navigation > li > a');
                }
            }, function () {
                $(this).removeClass('hover').find('ul').hide();
                Cufon.refresh('#header .navigation > li > a');
            });
        },
        contact: function () {

            //Info slideDowns for enquiry selection type
            var contact = $('#primary .contact'),
                content = contact.find('.equiry_content li');

            contact.find('select').change(function () {
                var index = $(this).find('option:selected').index();

                if (index === 0) {
                    content.slideUp(200);
                    return;
                }
                index--;

                content.eq(index).slideDown(150).siblings().hide();
            });

            sitecore('#primary .contact li');
        },
        masonary: function(){
            var nav = $('#header .navigation > li > ul');
                
            nav.children('li').addClass('mason');
                
            nav.masonry({
                itemSelector: '.mason',
                columnWidth: 245,
                gutterWidth: 10
            })
            nav.addClass('loaded').filter(':gt(2)').addClass('righter');
        },
        home: function () {
            var banner = $('#header .banner');

            banner.find('.slides').cycle({
                fx: 'scrollHorz',
                before: function (slide, next, options, forwardFlag) {
                    $(slide).find('.heading').fadeOut(200);
                    $(next).find('.heading').fadeIn(200);
                    banner.find('.buttons').hide();
                },
                after: function (slide, next, options, forwardFlag) {
                    banner.find('.buttons').fadeIn(100);
                },
                next: '#header .banner .forward',
                pause: 0,
                prev: '#header .banner .back',
                speed: 500,
                timeout: 9000
            });

            clearOnFocus('#content .job_search input', 'Keyword');
        },
        careers: function (url, buttonTxt, inputTxt, selectTxt) {
            var buttonText =  buttonTxt || 'Search',
                inputText = inputTxt || 'Search',
                selectText = selectTxt || 'Select location';
                
                
            Careers.search("pageUpSearch", url, " cw", "en", {
                filters: { "Keyword": "",
                    "Locations": ""
                }
            });
            //Set the old filter aside
            var oldSetFilter = Careers.setFilterData;

            Careers.setFilterData = function (type, returnedJson) {
                oldSetFilter(type, returnedJson);
                (function () {
                    //callback function
                    var search = $('#pageUpSearch'),
                        wrappers = search.find('.field-wrapper'),
                        keyword = search.find('.Keyword');

                    clearOnFocus(keyword, inputText);

                    dropDown('#pageUpSearch select').vjDropdown(true);
                    search.find('.dropdown em').html(selectText);
                    
                    $('#pageUpLinks').show();

                    wrappers.eq(2).addClass('buttons').append('<span>decal</span>').find('input').addClass('button').hover(function () {
                        $(this).parent().addClass('active');
                    }, function () {
                        $(this).parent().removeClass('active');
                    }).focus(function () {
                        $(this).parent().addClass('active');
                    }).blur(function () {
                        $(this).parent().removeClass('active');
                    }).click(function(){
                        if(keyword.val() == 'Keyword'){
							keyword.val('');
                        }
                    }).attr('value', buttonText);

                    //console.log(search.length + ' - ' + wrappers.length + ' - ' + keyword.length + ' - ' + search.find('select').length);
                } ());
            }

        },
        flash: function (language) {
            var flashVars = { dataPath: '/Services/MapDataXml.aspx', lang: language },
                params = {
                    allowScriptAccess: "sameDomain",
                    allowFullScreen: "true",
                    menu: "false",
                    scale: "noScale",
                    base: "/includes/flash/",
                    colorForeground: "#f9fcfd",
                    colorBackground: "#23374E",
                    colorTheme: "#c10926",                   
                    wmode: "opaque"
                },
                attributes = {
                    id: "InteractiveMap2011",
                    name: "InteractiveMap2011"
                };

            // Version numbers:
            //	Flash 8:	8.0.42.0
            //	Flash 9:	9.0.260.0
            // 	Flash 10:	10.0.45.2
            swfobject.embedSWF("/includes/flash/preloader.swf", "flash", "960px", "616px", "10.0.45.2", false, flashVars, params, attributes);
        }
    }
})();

/* $ extentions */
jQuery.fn.vjDropdown = function (selectMirror) {
    var selectReplace = selectMirror;

    return this.each(function () {
        var dropdown = $(this),
            current = dropdown.find('a:first'),
            list = dropdown.find('ul'),
            body = $('body, html'),
            close = function(){
                list.slideUp(200, function(){
                    dropdown.removeClass('active');
                });
                body.unbind('click');
            },
            open = function(){
                dropdown.addClass('active');
                list.slideDown(200);
                body.click(function(){
                    close();
                });
            };
            
        dropdown.click(function(){
            if(dropdown.is('.active')){
                close();
            } else {
                open();
            }
            return false;
        });

        list.find('a').click(function(){
            var that = $(this),
            ind;
            selectedVal = that.addClass('active').html();
            current.find('em').html(selectedVal);

            //If this is repacing a select it will look for a sibling select and change it.
            if (selectReplace) {
                var select = dropdown.siblings('select');
                ind = that.parent().index();

                select.find('option').removeAttr('selected').each(function () {

                    var $this = $(this);
                    if ($this.text() == selectedVal) $this.attr('selected', 'selected');

                });


                //select.find("option:contains('" + selectedVal + "')").attr('selected', 'selected');
                //need validation caller here.
                select.trigger('change');
                close();
                return false;
            }
            /*
            $.ajax(function(){
            // send up selectedVal to the pagination. and probably set a cookie.
            });
            */
        });
    });
};
