/**
 * Namespace "Common"
 * @class Common
 * @desc Subclass of Base
 */
Base.Common = function () {
    /**
    * function navFade,  for the fading effect in the navigation
    */
    function navSubFade() {
        $('#nav-sub ul li a:not(.active)')
			.css({ backgroundPosition: '0 -25px' })
			.bind('mouseover', function () {
			    $(this).stop().animate({ backgroundPosition: '(0 -90px)' }, { duration: 150 })
			})
			.bind('mouseout', function () {
			    $(this).stop().animate({ backgroundPosition: '(0 -25px)' }, { duration: 150 })
			})
    };

    function navFade() {
        $('#nav-main ul li a:not(.active)')
			.css({ backgroundPosition: "0 0" })
			.bind('mouseover', function () {
			    $(this).stop().animate({ backgroundPosition: "(0 -68px)" }, { duration: 150 })
			})
			.bind('mouseout', function () {
			    $(this).stop().animate({ backgroundPosition: "(0 0)" }, { duration: 150 })
			});
    };

    function navDots() {
        $('#nav-sub ul li:first').addClass('first');
        $('#nav-sub ul li a.active').closest('li').addClass('active');
        $('#nav-sub ul li a.active').closest('li').next('li').addClass('after');

        $('#nav-sub ul li a').mouseenter(function () {
            $(this).parent('li').next('li').find('.nav').addClass('clean')
        })
        $('#nav-sub ul li a').mouseleave(function () {
            $(this).parent('li').next('li').find('.nav').removeClass('clean')
        })
    }

    /**
    * function sitepicker,  to expand go to other site field
    */
    function sitePicker() {
        // open
        $('#sitepicker .foldin a').bind('click', function () {
            var picker = $(this).closest('#sitepicker');
            Base.Overlay.show({ closeOnClick: false }); // show overlay

            $('body').append('<div id="lb-sitepicker-container"><div id="lb-sitepicker-content" class="sitepicker"></div></div>'); // create window
            $('#lb-sitepicker-content').append(picker.children('.foldout').html()); // fill content with .foldin

            if (!Base.ieVersion)
                $('#lb-sitepicker-content').slideDown(150); // animate
            else
                $('#lb-sitepicker-content').show(); // just show in IE

            return false;
        });

        // close
        $('.sitepicker a.close').live('click', function () {
            if (Base.ieVersion == 7) {
                $('#lb-sitepicker-container').remove();
                Base.Overlay.hide();
            }
            else {
                $('#lb-sitepicker-content').closest('.sitepicker').slideUp(200, function () {
                    $('#lb-sitepicker-container').remove();
                    Base.Overlay.hide();
                });
            }

            return false;
        });
    };

    function clickNewsitem() {
        $('ul.overview-item li').click(function () {
            document.location = $(this).find('a').attr('href');
        })
    };


    /**
    * function search,  to expand search box in the header
    */
    function searchBox() {
        // find search id
        $('#search .box a').bind('click', function () {
            var box = $(this).closest('.box');

            if (!$(box).hasClass('close')) {
                //add class close to change the link icon and open the container for the search box
                $(box).addClass('close').next('.open').slideDown(100, function () {
                    $(this).find(':text').focus();
                });
            } else {
                // if it has class close and it gets clicked, remove class and close the container for the search box
                $(box).removeClass('close').next('.open').slideUp(100);
            }
            return false;
        });
    };


    /**
    * Initialize all the tooltip on the site
    */
    function tooltips() {
        $.fn.infoToolTip.defaults.offsetX = 5;
        $('.tooltip').infoToolTip();
    }

    function imageSlideshow() {
        $('.slideshow').imageSlideShow();
    }


    // Add story-opener to .story-block, hide the story, have the story-opener open the story and then add a close button to it
    // deze functie is vervallen, js kan ws weg, maar ff wachten tot einde project
    function storyBlockToggler() {
        $('.story-block .quote').click(function () {
            $('.story').slideDown('fast'), $('.story').css('background:#ff6600;');
        });

        $('.story-closer').click(function () {
            $('.story').slideUp('fast');
        });
    }


    // Hide the mailform, have the mail-vestia-opener open it and then add a close button 
    function mailVestiaToggler() {
        $('.mail-vestia-opener').live('click', function () {
            // var offset = $(this).closest('ul').offset(); 
            // $(this).closest('ul.link').next('.mail-vestia').clone().removeClass('hide').prependTo($('body')).wrap('<div id="contact-popup" class="column"></div>');									
            // $('#contact-popup').css({left:offset.left, top:offset.top}).hide().slideDown('fast');

            $(this).closest('div').slideUp('fast');
            $(this).closest('.contact').find('.mail-vestia').slideDown('fast');

            return false;
        });

        $('.mail-vestia-closer').live('click', function () {
            //$('#contact-popup').slideUp('fast', function(){
            //	$(this).remove();
            $(this).closest('.contact').find('.contact-content').slideDown('fast');
            $(this).closest('.mail-vestia').slideUp('fast');
        });
    }

    // Hide the call me back form, have the callback-vestia-opener open it and then add a close button 
    function callbackVestiaToggler() {
        $('.callback-vestia-opener').live('click', function () {

            // var offset = $(this).closest('ul').offset(); 
            // $(this).closest('ul.link').next('.mail-vestia').clone().removeClass('hide').prependTo($('body')).wrap('<div id="contact-popup" class="column"></div>');									
            // $('#contact-popup').css({left:offset.left, top:offset.top}).hide().slideDown('fast');
            
            $(this).closest('div').slideUp('fast');
            $(this).closest('.contact').find('.callback-vestia').slideDown('fast');

            return false;
        });

        $('.callback-vestia-closer').live('click', function () {
            //$('#contact-popup').slideUp('fast', function(){
            //	$(this).remove();

            $(this).closest('.contact').find('.contact-content').slideDown('fast');
            $(this).closest('.callback-vestia').slideUp('fast');
        });
    }

    function infoCordion() {
        $('ul.infocordion').infoCordion({ titleSel: 'li > a:not(li li a)', contentSel: 'div.faq-content' });
    }

    function initDatePicker() {

        $('input.datepicker').each(function () {
            var opts = { displayClose: 1 }

            // only date is past is selectable
            if ($(this).hasClass('past')) {
                opts.startDate = '01/01/2009';
                opts.endDate = (new Date()).asString();
            }
            $(this).datePicker(opts);
        });
    }

    /** 
    * function to create, read and erase cookies
    */
    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }


    /** 
    * function to enlarge the fontsize
    */
    function fontEnlarging() {
        $('a.enlarge').click(function () {
            $('body').removeClass('largest').addClass('enlarge');
            createCookie('fonts', 'enlarge', 31)
            return false;
        })
        $('a.largest').click(function () {
            $('body').removeClass('enlarge').addClass('largest');
            createCookie('fonts', 'largest', 31)
            return false;
        })
        $('a.standard').click(function () {
            $('body').removeClass('enlarge').removeClass('largest');
            eraseCookie('fonts')
            return false;
        })
        $('body').addClass(readCookie('fonts'));
    }

    /**
    * Includes flash movie on homepage
    */
    function initHomeFlash() {
        if ($('#home-flash').length == 1) {
            //var tool = swfobject.getQueryParamValue("tool");

            var flashvars = { urlxml: Base.paths.homeflash + '/xml/data.xml' };
            var params = { wmode: 'transparent' };
            swfobject.embedSWF(Base.paths.homeflash + '/main.swf', 'home-flash', '940', '285', '7.0.0', Base.paths.homeflash + '/includes/expressInstall.swf', flashvars, params);
        }
    }

    /**
    * Attach the GoogleAnalyticsMeasurement to all links
    */
    function initAnalysticsLinkCrawler() {
        /*
        Zie Google documentatie over event tracking:
        http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
        */

        /**
        * Init the link crawler
        * url* Example of a match (regular expression, tracker):
        * [/regex/, {"category":'category', "action":'action', "label":'label', "value":0}]
        * -> label and value are optional
        * 
        * You may give a callback function as a value. Callback functions receive 1 attribute:
        * the href of the link. It should return the proper value.
        * 
        * NOTE: The first match will be tracked! So the order of matchers matters!
        * More documentation in jquery.analyticsLinkCrawler.js
        */
        // global variables
        // ------ initialise here -------
        var baseurl = 'http://www.vestia.nl/',
	    homepage_suffix = '/Pages/default',
	    crawl_this = '#contentwrapper', // you can add more selectors with comma's, e.g: '#contentwrapper, .mydiv'
	    options = { ignoreSelector: '.nocrawl' }, // within "crawl_this", ignore links with ignoreSelector
        // ---------- end init ----------

	    companies = ['Delft', 'DenHaagScheveningen', 'DenHaagZuidOost', 'DenHaagZuidWest', 'NoordNederland', 'Nootdorp', 'RotterdamFeijenoord', 'RotterdamHoogvliet', 'RotterdamNoord', 'RotterdamZuid', 'Westland', 'Zoetermeer', 'ZuidNederland', 'Zuidplas'],
	    companyLabels = ['Delft', 'Scheveningen', 'Den Haag-ZO', 'Den Haag-ZW', 'Noord-NL', 'Nootdorp', 'Rdam-Feijenoord', 'Rdam-Hoogvliet', 'Rdam-N', 'Rdam-Z', 'Westland', 'Zoetermeer', 'Zuid-NL', 'Zuidplas'];

        // request variables
        var page_url = location.href;

        // get company name
        var search_to = page_url.indexOf('/', baseurl.length),
	    company = page_url.substring(baseurl.length, (search_to > baseurl.length) ? search_to : baseurl.length),
	    companyId = $.inArray(company, companies);
        company = (companyId > -1) ? company : '';

        // check if current page is a homepage
        var homepageRegex = new RegExp('^' + baseurl + (company ? company + '/' : '') + homepage_suffix),
	    page_title = (homepageRegex.test(page_url)) ? 'homepage' : document.title;

        // the category for this request
        var category = companyLabels[companyId] || 'Vestia Groep';

        // Start de crawler
        $(crawl_this).analyticsLinkCrawler([
		[/^mailto:/i, { // mailto
		    "category": category,
		    "action": 'mailto',
		    "label": function (url) {
		        return url.substr(url.indexOf(':') + 1) + '_' + page_title;
		    }
		}],

		[/\.pdf$/, { // pdf files (must end with .pdf)
		    "category": category,
		    "action": 'pdf',
		    "label": function (url) {
		        return url.substr(url.lastIndexOf('/') + 1) + '_' + page_title;
		    }
		}],

		[/\.docx?$/, { // word files (must end with .doc or .docx)
		    "category": category,
		    "action": 'word',
		    "label": function (url) {
		        return url.substr(url.lastIndexOf('/') + 1) + '_' + page_title;
		    }
		}],

		[/\.xlsx?$/, { // excel files (must end with .xls or .xlsx)
		    "category": category,
		    "action": 'excel',
		    "label": function (url) {
		        return url.substr(url.lastIndexOf('/') + 1) + '_' + page_title;
		    }
		}],

		[/\.pptx?/, { // powerpoint files (must end with .ppt or .pptx)
		    "category": category,
		    "action": 'powerpoint',
		    "label": function (url) {
		        return url.substr(url.lastIndexOf('/') + 1) + '_' + page_title;
		    }
		}],

		[/.+twitter.com/i, { // twitter.com
		    "category": category,
		    "action": 'twitter',
		    "label": function (url) {
		        return url.substr(url.lastIndexOf('/') + 1) + '_' + page_title;
		    }
		}],

		[/.+youtube\./i, { // youtube
		    "category": category,
		    "action": 'youtube',
		    "label": function (url) {
		        return url + '_' + page_title;
		    }
		}],

		[/^(?!.*vestia\.nl)/i, { // link zonder vestia.nl
		    "category": category,
		    "action": 'outbound',
		    "label": function (url) {
		        return url.substr((url.indexOf('www') || 0)) + '_' + page_title;
		    }
		}]
	], options);
    }

    /** 
    * Registers the necessary postback event before the infocordion click event so the postback will occur.
    */
    function registerFaqPostback() {
        $('ul.infocordion li > a:not(li li a)').click(function () {
            if (this.href && !$(this).hasClass('active')) {
                $faqId = $(this).parent().find('input[type=hidden]').attr("value");
                if ($faqId != null) {
                    Vestia.nl.Views.VestiaFAQService.FAQService.QuestionRead($faqId);
                }
            }
        });
        return true;
    }

    return {

        /**
        * Initialize this Class
        */
        init: function () {
            fontEnlarging();
            navSubFade();
            navFade();
            navDots()
            searchBox();
            sitePicker();
            tooltips();
            mailVestiaToggler();
            callbackVestiaToggler();
            registerFaqPostback();
            infoCordion();
            imageSlideshow();
            initDatePicker();
            $('div.tabs').infoTabs();
            $('#service').infoKwick();
            initHomeFlash();
            clickNewsitem();
            initAnalysticsLinkCrawler();
        }
    };
} ();

/* Initialize this class */
Base.register(Base.Common.init);

