﻿

var CB = {

    init:
    function() {

        $(".form-container input[type=text]").keydown(CB.submitOnEnterPress);
        $(".toggle").click(CB.toggle);
        $("#contentwrapper a[rel=external]").click(CB.openInNewWindow);
        $(".clickable-rows tr").click(CB.handleTableRowClick);
        if (CB.IE6) {
            $(".clickable-rows tr").mouseover(function() { $(this).addClass("hover"); });
            $(".clickable-rows tr").mouseout(function() { $(this).removeClass("hover"); });
        }
        $("tr:nth-child(even)").addClass("alternate");
        $(".print-page").click(function() { window.print(); });

        CB.customFadeIn($("#infobox"), 400);
        CB.setAdditionalBrowserInfo();
		CB.formEnhancers();
        CB.NewsFetcher.init();
        CB.GAQ.init();

    },

    formEnhancers: function() {
        // Adds a class each element with the attribute type="text".
        // EPiServer does not print this attribute by default and since
        // we need to be able to fetch these elements in CSS by all
        // browsers we need a class instead of applying the attribute.
        // Only xForm elements are targeted.
        $('.xform input').each(function() {
            if ($(this).attr('type') === 'text') {
                $(this).addClass('type-text');
            }
        });

        // ...
        $('.xform input[type=submit]').addClass('type-submit');
        
        // Mandatory information.
        var span = $('<span></span>'); // span template
        $('.xform td').each(function() {
            if ($(this).find('input, textarea, select').not('input[type=submit]').length) {
                var x = span.clone();
                var v = $(this).find('.xformvalidator');
                if (v.length) {
                    v.wrap('<div class="man-wrap"></div>');
                    x.addClass('man');
                }
                x.addClass('input-info').css({ height: ($(this).height()-4) }).appendTo($(this));
            }
        });

    },

    submitOnEnterPress:
    function(evt) {

        if (evt.keyCode === 13) {
            evt.preventDefault();
            $(this).parents(".form-container").find("input[type=submit]").trigger("click");
            return false;
        }
    },

    IE6:
    function() {
        return document.all && /MSIE\s?6/.test(navigator.userAgent);
    },

    toggle:
    function(evt) {

        var elmId = "#" + this.className.replace(/.*toggle-id-([\w\_\-]+).*/, "$1");
        var elm = $(elmId);

        if (elm.is(":hidden")) {
            CB.customFadeIn(elm, 400);

        }
        else {
            CB.customFadeOut(elm, 400);
        }
        return false;
    },

    setAdditionalBrowserInfo:
    function() {
        ua = navigator.userAgent.toLowerCase();
        is = function(t) { return ua.indexOf(t) != -1; },
		h = document.getElementsByTagName('html')[0],
		b = (!(/opera|webtv/i.test(ua)) && /msie (\d)/.test(ua)) ? ('ie ie' + RegExp.$1)
			: is('firefox/2') ? 'gecko ff2' : is('firefox/3') ? 'gecko ff3' : is('gecko/') ? 'gecko' : is('opera/9') ? 'opera opera9' : /opera (\d)/.test(ua) ? 'opera opera' + RegExp.$1 : is('konqueror') ? 'konqueror' : is('applewebkit/') ? 'webkit safari' : is('mozilla/') ? 'gecko' : '',
		os = (is('x11') || is('linux')) ? ' linux' : is('mac') ? ' mac' : is('nt 5') ? ' xp' : is('win') ? ' win' : '';
        var c = b + os + ' js';
        h.className += h.className ? ' ' + c : c;

    },

    openInNewWindow:
    function(evt) {
        var event = (!evt) ? window.event : evt;
        if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey)
            return true;
        else {
            var oWin = window.open(this.getAttribute('href'), '_blank');
            if (oWin) {
                if (oWin.focus)
                    oWin.focus();
                return false;
            }
            oWin = null;
            return true;
        }
    },

    handleTableRowClick: function(evt) {
        var link = $("a:first", this)[0];

        if (link) {
            location.href = link.href;
        }
    },

    customFadeIn:
    function(elm, speed) {
        elm.fadeIn(speed, function() {
            if (jQuery.browser.msie) {
                $(this).get(0).style.removeAttribute('filter');
            }
        });
    },

    customFadeOut:
	function(elm, speed) {
	    elm.fadeOut(speed, function() {
	        if (jQuery.browser.msie) {
	            $(this).get(0).style.removeAttribute('filter');
	        }
	    });
	}

};

/**
 * News fetcher from AlertIR
 */
CB.NewsFetcher = (function() {
    
    var container = null;
    var Setup = {
        url: 'http://investors.nobina.com/index.php?',
        landingPage: '',
        Params: {
            p: 'press',
            s: 'json',
            afw_lang: '', // read from the container element based on EPiServer language branch variable.
            afw_callback: 'CB.NewsFetcher.callback'
        },
        Options: {
            maxItems: 4
        }
    };
    
    function formatDate(date) {
        return date.substring(0, 10);
    }
    
    function callback(result) {
        var cn = CB.NewsFetcher;
        var ol = $('<ol></ol>').addClass('news');
        var data = result.data;
        var $li = $('<li></li>');
        
        for (var i in data) {
            var d = data[i];
            var published = d.published;
            var headline = d.headline;
            if (published !== null && headline !== null) {
                var li = $li.clone();
                var span = $('<span></span>').html(formatDate(published)).appendTo(li);
                var aID = d.id;
                var a = $('<a></a>').attr('href', Setup.landingPage + d.id).html(headline).appendTo(li);
                li.appendTo(ol);
            }

            if (i === (Setup.Options.maxItems - 1)) break;
        }
        container.html(ol);
    }
    
    function fetchJSON() {
        var params = $.param(Setup.Params);
        $.getJSON(Setup.url + params + '&callback=?'); // &callback=? enables JSONP
    }
    
    return {
        callback: callback,
        init: function() {

            Setup.Options.maxItems = parseInt(CB.alertIRMaxItems); // Inside the startpage template
            Setup.landingPage = $('.AlertIRLandingPage').attr('href') + '?newsID=';
            
            container = $('div.AlertIDNewsList');
            if (container.length) {
                Setup.Params.afw_lang = container.attr('lang');
                fetchJSON();
            }
        }
    }
})();

/**
 *	Helper functions
 */
CB.Utils = (function() {
	
	function getLanguageBranch() {
		return location.pathname.split('/')[1];
	}
	
	function getCountryNameBranch() {
		return location.pathname.split('/')[2];
	}
	
	return {
		getLanguageBranch: getLanguageBranch,
		getCountryNameBranch: getCountryNameBranch
	};
	
})();

/**
 * Google Analytics utils
 */
CB.GAQ = (function() {
    
    // Categories
    var Category = {
       offerPage: 'Offer page',
       search: 'Search page'
    };
    
    // Actions
    var Action = {
        offerSubmitForm: 'Offer page submitted',
        search: 'Searching'
    };
    
    // Push a track event to Google Analytics
    function trackEvent(category, action, label) {
        _gaq.push(['_trackEvent', category, action, label]);
    }
    
	/*
	*	Form tracking is used when we need to track a submission of a form.
	*	If the page contains an input with a chosen class, grab the value
	*	and push it to Google Analytics. The input is introduced after a
	*	postback to the server since we can't call Google Analytics at the
	*	same time as the form is submitted and to only save successful submits.
	*/
    function setupFormTracking() {
        // --- Track form submissions of type quote inquery form (offer page) ---
        var $offerPage = $('.gaq_offer-page');
        if($offerPage.length) {
            var label = $offerPage.val(); // Name of the page
            trackEvent(Category.offerPage, Action.offerSubmitForm, label);
        }
        
        // --- Track search queries. ---
        var $searchTerm = $('.gaq_search-term');
        if($searchTerm.length) {
            var label = $searchTerm.val(); // Query
            trackEvent(Category.search, Action.search, label);
        }
    }
    
    // Initialize
    function init() {
		setupFormTracking();
    }
    
    return {
        init: init
    };
    
})();

$(document).ready(CB.init);


