jQuery(function($){

    var host = "ajax.api-web.org";
    var methodName = "blast";
    var club = '';
    var carousel_arr = [];
    var lang = localization[country];
    var pageSwitchTimer = null;
    
    (function filterIE(){
        if ($.browser.msie) {
            $('#footer').css('background', '#202020');
        }
    })();
    
    (function init(){
        $('#cc').click(function(){
            updateContent('headernav_item_3');
        });
        if (category == 'home') {
            pageSwitchTimer = setTimeout(function(){
                location.href = "fun.php";
            }, 10000);
        }
    })();
    
    (function setCarouselItems(){
        var container = $('<ul></ul>');
        var teaserItems = lang.teaserConfig[country][category];
        var teaserLength = teaserItems.length;
        for (var n = 0; n < teaserLength; n++) {
            if (category == 'home') {
                var src = '../img/teaser/' + country + '/' + country + '_' + teaserItems[n] + '_0.png';
                var item = $('<li></li>');
                var href = getCategoryByService(teaserItems[n], country) + '.php';
                var link = $('<a></a>').attr({
                    href: href
                });
                var img = $('<img></img>').attr({
                    src: src,
                    rel: teaserItems[n]
                });
                link.append(img);
                item.append(link);
            }
            else {
                var src = '../img/teaser/' + country + '/' + country + '_' + teaserItems[n] + '_0.png';
                item = $('<li></li>');
                var link = $('<div></div>').attr({
                    rel: teaserItems[n]
                });
                var img = $('<img></img>').attr({
                    src: src,
                    rel: teaserItems[n]
                });
                link.append(img);
                item.click(function(){
                    showOverlay();
                    handleClub($(this).children('div')[0]);
                });
                item.append(link);
            }
            container.append(item);
        }
        $('#carousel').append(container);
    })();
    
    (function buildFooterLists(){
        var lists = lang.serviceConfig[country];
        var container = $('#service_lists');
        for (var n = 0; n < lists.length; n++) {
            var list = $('<ul></ul>').addClass('service-list');
            var items = lists[n].items;
            var title = $('<li></li>').addClass('service-list-title').text(lists[n].title);
            var cat = $('<li></li>').addClass('service-list-cat').text(lists[n].category)
            list.append(title);
            list.append(cat);
            for (var i = 0; i < items.length; i++) {
                var data = items[i];
                var listItem = $('<li></li>').addClass('service-list-item').text(data.name);
                if (category != 'home') {
                    var link = $('<a></a>').attr({
                        href: '#',
                        rel: data.club
                    });
                    link.click(function(){
                        handleListLinks(this);
                        handleClub(this);
                        return false;
                    });
                    link.append(listItem);
                    list.append(link);
                }
                else {
                    var link = $('<a></a>').attr({
                        href: lists[n].category + '.php',
                        rel: data.club
                    });
                    link.append(listItem);
                    list.append(link);
                }
            }
            container.append(list);
        }
    })();
    
    function updateContent(id){
        var id = id.replace(/^footer/g, "header");
        $('#info_content').attr('style', '');
        if ($('#info_slide')) {
            $('#info_slide').remove();
            $('#info_nav').html('');
        }
        if (typeof pageSwitchTimer != null) {
            clearTimeout(pageSwitchTimer);
        }
        $('#player').css('display', 'none');
        $('#info_content').html('');
        if ($('#info_content').hasClass('fullsize')) {
            $('#info_content').removeClass('fullsize');
        }
        if ($('#info_container').hasClass('alternate')) {
            $('#info_container').removeClass('alternate');
        }
        var content = lang.infoContentConfig[country][id].content;
        var container = $('<div></div>').attr('id', 'info_slide').addClass('info-content-wrapper');
        if (content.length > 1) {
            for (var n = 0; n < content.length; n++) {
                var wrapper = $('<div></div>').addClass('info-content-wrapper');
                if (lang.infoContentConfig[country][id].background) {
                    wrapper.css({
                        background: 'url(../img/' + lang.infoContentConfig[country][id].background + ') no-repeat'
                    })
                }
                else {
                    wrapper.addClass('standard')
                }
                var item = $('<div></div>').addClass('info-content-item').html(content[n]);
                if (lang.infoContentConfig[country][id].fullsize) {
                    item.addClass('fullsize');
                }
                if (lang.infoContentConfig[country][id].width) {
                    item.css({
                        width: lang.infoContentConfig[country][id].width + 'px !important'
                    });
                }
                wrapper.append(item);
                container.append(wrapper);
            }
            $('#info_container').prepend(container);
            if ($f('player')) {
                $f('player').stop();
            }
        }
        else {
            var infoContentContainer = $('#info_content');
            if (lang.infoContentConfig[country][id].fullsize) {
                infoContentContainer.addClass('fullsize');
                $('#info_container').addClass('alternate')
            }
            if (lang.infoContentConfig[country][id].top) {
                infoContentContainer.css({
                    paddingTop: lang.infoContentConfig[country][id].top + 'px'
                });
            }
            if (lang.infoContentConfig[country][id].width) {
                $('#info_content').css({
                    width: lang.infoContentConfig[country][id].width + 'px'
                });
            }
            infoContentContainer.html(content[0]);
        }
        if (!$('#info_container').hasClass('active')) {
            $('#info_container').addClass('active');
        }
        if ($('#overlay').hasClass('active')) {
            $('#overlay').removeClass('active')
        }
        $('.' + category).removeClass('active');
        if ($('#content_slide')) {
            $('#content_slide').cycle('stop');
        }
    }
    
    (function initNav(){
        var topnavContainer = $('<ul></ul>').attr('id', 'topnav-list');
        var subNavContainerHeader = $('<ul></ul>').addClass('subnav-list');
        var subNavContainerFooter = $('<ul></ul>').addClass('subnav-list');
        var nav = lang.navConfig[country];
        var x;
        for (x in nav) {
            if (x == 'topNav') {
                var n;
                var count = 1;
                for (n in nav[x]) {
                    if (count != 1) {
                        var separator = $('<li></li>').addClass('topnav-sep');
                        separator.append($('<img />').attr('src', '../img/topnav_sep.gif'));
                        topnavContainer.append(separator);
                    }
                    var topnavItem = $('<li></li>').addClass('topnav-item ' + n);
                    if (n == 'home') {
                        topnavItem.append($('<a></a>').attr('href', 'index.php').text(nav[x][n]));
                    }
                    else {
                        topnavItem.append($('<a></a>').attr('href', n + '.php').text(nav[x][n]));
                    }
                    topnavContainer.append(topnavItem);
                    count++;
                }
            }
            else {
                var i = 1;
                count = 1;
                for (n in nav[x]) {
                    if (count != 1) {
                        subNavContainerHeader.append($('<li></li>').addClass('subnav-sep').text('|'));
                        subNavContainerFooter.append($('<li></li>').addClass('subnav-sep').text('|'));
                    }
                    var subnavItemHeader = $('<li></li>').addClass('subnav-item').attr('id', 'headernav_item_' + i).text(nav[x][n]);
                    subnavItemHeader.click(function(){
                        updateContent($(this).attr('id'));
                    });
                    var subnavItemFooter = $('<li></li>').addClass('subnav-item').attr('id', 'footernav_item_' + i).text(nav[x][n]);
                    subnavItemFooter.click(function(){
                        updateContent($(this).attr('id'));
                    });
                    subNavContainerHeader.append(subnavItemHeader);
                    subNavContainerFooter.append(subnavItemFooter);
                    i++;
                    count++;
                }
            }
        }
        $('#header').append(subNavContainerHeader);
        $('#topnav').append(topnavContainer);
        $('#footernav').append(subNavContainerFooter);
    })();
    
    (function setNav(){
        if (mode == null) {
            var activeNav = $('.' + category);
            if (!activeNav.hasClass('active')) {
                activeNav.addClass('active');
            }
        }
    })();
    
    (function setText(){
        var text = lang.textConfig[country][category];
        var x;
        for (x in text) {
            var container = $('#' + x)[0];
            if (container) {
                $(container).html(text[x]);
            }
        }
    })();
    
    (function initCountryList(){
        var list = $('<ul></ul>').attr('id', 'country_list');
        var x;
        for (x in countryList) {
            var item = $('<li></li>').attr('rel', x).addClass('country-list-item').text(countryList[x]);
            item.click(function(){
                location.href = '../' + $(this).attr('rel');
            });
            list.append(item);
        }
        $('#country_list_wrapper').append(list);
        $('#countrySelect').html(countryList[country]);
        $('#countrySelect').click(function(){
            var wrapper = $('#country_list_wrapper');
            if (!wrapper.hasClass('active')) {
                wrapper.addClass('active');
            }
            else {
                wrapper.removeClass('active');
            }
        })
        $('.country-list-item').mouseout(function(){
            hoverTimer = setTimeout(function(){
                $('#country_list_wrapper').removeClass('active');
            }, 1000);
        });
        $('.country-list-item').mouseenter(function(){
            clearTimeout(hoverTimer);
        });
    })();
    
    (function setCopyright(){
        var date = new Date();
        date = date.getFullYear();
        $('#copy').html('&copy;' + date + ' Mobile in Motion');
    })();
    
    (function initPlayer(){
        if (category != 'home' && mode == null) {
            flowplayer("player", {
                src: "../util/flowplayer.commercial-3.2.5.swf",
                bgcolor: '#ffffff'
            }, {
                clip: {
                    autoPlay: true,
                    autoBuffering: true,
                    bufferLength: 10,
                    url: '../img/vid/' + lang.vidConfig[country][category]
                },
                key: ['#@cb2aaeb666c158312a0', '#@33e5fb044c32b761ded']
            });
        }
    })();
    
    var carousel = $('#carousel ul');
    carousel.jcarousel({
        scroll: 1,
        start: 1,
        initCallback: carouselInitCallback,
        itemVisibleInCallback: {
            onBeforeAnimation: carouselInCallback
        },
        itemVisibleOutCallback: {
            onAfterAnimation: carouselOutCallback
        },
        wrap: 'circular'
    });
    
    function carouselInitCallback(carousel){
        $.each($('#carousel ul').children(), function(){
            carousel_arr.push($(this).html());
        });
        $('.jcarousel-next,.jcarousel-prev').insertAfter('#carousel');
        setCarouselHover();
        initAutoSlide(carousel);
    }
    
    function carouselInCallback(carousel, item, i, state, evt){
        var idx = carousel.index(i, carousel_arr.length);
        new_item = carousel.add(i, carousel_arr[idx - 1]);
        setCarouselHover(new_item);
    }
    
    function carouselOutCallback(carousel, item, i, state, evt){
        carousel.remove(i);
    }
    
    function setCarouselHover(obj){
        if (!obj) {
            var items = $('.jcarousel-list li');
            var len = items.length;
            var teaser = lang.teaserConfig[country][category];
            if (teaser) {
                for (var n = 0; n < len; n++) {
                    var item = $(items[n]);
                    var img = item.find('img');
                    var oldSrc = img.attr('src');
                    var newSrc = '../img/teaser/' + country + '/' + country + '_' + teaser[n] + '_1.png';
                    item.bind('mouseover', {
                        newSrc: newSrc
                    }, function(e){
                        $(this).find('img').attr('src', e.data.newSrc);
                    });
                    item.bind('mouseout', {
                        oldSrc: oldSrc
                    }, function(e){
                        $(this).find('img').attr('src', e.data.oldSrc);
                    });
                }
            }
        }
        else {
            var item = $(obj);
            var img = item.find('img');
            var oldSrc = img.attr('src');
            var newSrc = '../img/teaser/' + country + '/' + country + '_' + img.attr('rel') + '_1.png';
            item.bind('mouseover', {
                newSrc: newSrc
            }, function(e){
                $(this).find('img').attr('src', e.data.newSrc);
            });
            item.bind('mouseout', {
                oldSrc: oldSrc
            }, function(e){
                $(this).find('img').attr('src', e.data.oldSrc);
            });
        }
    }
    
    function getCategoryByService(serviceName, iso){
        var x;
        var services = lang.teaserConfig[iso];
        for (x in services) {
            if (x != 'home') {
                var len = services[x].length;
                for (var n = 0; n < len; n++) {
                    if (services[x][n] == serviceName) {
                        return x;
                    }
                }
            }
        }
    }
    
    (function initDownloadMask(){
        $('#btnSend').click(function(){
            sendCheck('input_number', 'maskCheckbox');
        });
        $('#input_number').focus(function(){
            if ($(this).val() == '') {
                $(this).val(lang.serviceReq.numberPrefix);
            }
        });
    })();
    
    (function preload(){
        var teaserItems = lang.teaserConfig[country][category];
        var teaserLength = teaserItems.length;
        for (var n = 0; n < teaserLength; n++) {
            var src = '../img/teaser/' + country + '/';
            var img = new Image();
            img.src = src + country + '_' + teaserItems[n] + '_1.png';
        }
        var img = new Image();
        img.src = '../img/bg_info_container.png';
        img = new Image();
        img.src = '../img/bg_tcs2.png';
    })();
    
    function sliderNext(){
        $('#content_slide').cycle('next');
        $('.secure-check error-check').removeClass('error-check');
        $('.input-content error').removeClass('error');
        timeoutSlider = setTimeout(sliderNext, 8000);
    }
    
    handlemail = function(){
        var isError = false;
        var errorItems = [];
        unmarkField();
        var msg = $('#information');
        var name = $('#input_name').val().trim();
        var subject = $('#select_subject').val();
        var email = $('#input_email').val().trim();
        var number = $('#input_contact_number').val().trim();
        var text = $('#input_text').val().trim();
        if (msg.hasClass('success')) {
            msg.removeClass('success');
            msg.addClass('error');
        }
        if (!msg.hasClass('error')) {
            msg.addClass('error');
        }
        if (!name) {
            isError = true;
            errorItems.push($('#name')[0]);
        }
        if (subject == 'choose') {
            isError = true;
            errorItems.push($('#subject')[0]);
        }
        if (!email) {
            isError = true;
            errorItems.push($('#email')[0]);
        }
        if (!number || isNaN(number)) {
            isError = true;
            number = "";
            errorItems.push($('#number')[0]);
        }
        if (!text) {
            isError = true;
            errorItems.push($('#contact_text')[0]);
        }
        if (isError) {
            markField(errorItems);
        }
        if (!isError) {
            jQuery.ajax({
                url: '../util/sendmail.php',
                type: "POST",
                data: {
                    name: name,
                    subject: subject,
                    mail: email,
                    number: number,
                    text: text,
                    countryMail: lang.countryMail
                },
                success: function(data){
                    $('#input_name').val('');
                    $('#select_subject').val('choose');
                    $('#input_email').val('');
                    $('#input_contact_number').val('');
                    $('#input_text').val('');
                },
                error: function(){
                }
            });
        }
    }
    
    function markField(items){
        markedItems = items;
        $.each(items, function(){
            $(this).addClass('marked-field');
        });
    }
    
    function unmarkField(item){
        if (item) {
            $(item).removeClass('marked-field');
        }
        else {
            if (typeof markedItems != 'undefined') {
                $.each(markedItems, function(){
                    $(this).removeClass('marked-field');
                });
            }
        }
    }
    
    showOverlay = function(){
        $('#overlay').addClass('active');
        if ($('#info_container').hasClass('active')) {
            $('#info_container').removeClass('active')
        }
        $('#player').css('display', 'none');
        $f().stop();
    }
    
    handleContent = function(id){
        updateContent(id);
    }
    
    function initAutoSlide(carousel){
        $('.jcarousel-prev').bind('click', function(){
            clearTimeout(autoSlide);
            if (typeof pauseAutoSlide != 'undefined') {
                clearTimeout(pauseAutoSlide);
            }
            pauseAutoSlide = setTimeout(doAutomaticSlide, 20000);
        });
        $('.jcarousel-next').bind('click', function(){
            clearTimeout(autoSlide);
            if (typeof pauseAutoSlide != 'undefined') {
                clearTimeout(pauseAutoSlide);
            }
            pauseAutoSlide = setTimeout(doAutomaticSlide, 20000);
        });
        slide = carousel;
        autoSlide = setTimeout(doAutomaticSlide, 5000);
    }
    
    function doAutomaticSlide(){
        slide.next();
        autoSlide = setTimeout(doAutomaticSlide, 5000);
    }
    
    handleListLinks = function(obj){
        var selectedCat = $(obj).parent().find('.service-list-cat').text().toLowerCase();
        if (selectedCat == category) {
            showOverlay();
        }
        else {
            location.href = selectedCat + '.php';
        }
    }
    
    handleClub = function(obj){
        var service = $(obj).attr('rel').replace(/_2$/g, '');
        if (!service.match(/_/)) {
            service = lang.serviceReq.prefix + service + lang.serviceReq.suffix;
        }
        club = service;
    }
    
    sendCheck = function(numberId, checkBoxId){
        if (numberId.match(/input_content/) || lang.useServiceDefault) {
            club = 'default';
        }
        $('.input-content.error').removeClass('error');
        $('.secure-check.error-check').removeClass('error-check');
        var isError = false;
        var inputNumber = $('#' + numberId);
        var checkbox = $('#' + checkBoxId);
        var number = inputNumber.val();
        if (isNaN(number) || number == "") {
            inputNumber.addClass('error');
            isError = true;
            console.log(isError);
        }
        if (!checkbox.is(':checked')) {
            checkbox.parent().addClass('error-check');
            isError = true;
        }
        if (isError) {
            return;
        }
        else {
            $('.input-content.error').removeClass('error');
            $('.secure-check.error-check').removeClass('error-check');
            sendWebBlast(number);
        }
    }
    
    sendWebBlast = function(number){
        if (club == 'default' || club == '') {
            club = lang.serviceDefault;
        }
        if (number) {
            $.ajax({
                url: 'http://' + host + '/app/rpc',
                data: {
                    method: methodName,
                    number: number,
                    country: country,
                    service: club
                },
                dataType: 'jsonp',
                jsonpCallback: 'jsonpCallback'
            });
        }
    }
    
    handleSuccess = function(){
        if (category == 'home') {
            $('.content-wrapper').addClass('hidden');
            $('#content_success').addClass('active');
            $('#content_slide').cycle('pause');
            clearTimeout(timeoutSlider);
            timeoutSlider = setTimeout(restartSlider, 10000);
            $('.input-content').val('');
        }
        else {
            $('#send_mask').addClass('no-bg');
            $('#maskContent').addClass('hidden');
            $('#maskSuccessContainer').addClass('active');
            setTimeout(resetDownloadMask, 10000);
        }
    }
    
    function resetDownloadMask(){
        $('#send_mask').removeClass('no-bg');
        $('#maskSuccessContainer').removeClass('active');
        $('#maskContent').removeClass('hidden');
    }
    
    function pauseSlider(){
        $('#content_slide').cycle('pause');
        clearTimeout(timeoutSlider);
        timeoutSlider = setTimeout(sliderNext, 20000);
    }
    
    function restartSlider(){
        $('#content_success').removeClass('active');
        $('.content-wrapper').removeClass('hidden');
        sliderNext();
        
    }
    
});

function jsonpCallback(data){
    handleSuccess();
}

var countryList = {
    sg: 'Singapore',
    id: 'Indonesia',
    za: 'South Africa',
    es: 'Spain'
};

