var $j = jQuery;

$j(document).ready(function(){

    var re = new RegExp(".*\\/triodosforms\\/.*\\.seam");
    var formsMatch = re.exec(document.location);
    if(formsMatch == null && typeof(_gaq) != 'undefined'){// Only on non-form pages
        oscParameterName = 'osc';
        oscParameterNameValue = getUrlVars()[oscParameterName];
        if(oscParameterNameValue !== undefined) {
            _gaq.push(['_setCustomVar', 1, 'On site campaign', oscParameterNameValue, 2]);
        }
        _gaq.push(['_trackPageview']);
    }

    addLinkClasses();
    addCampaignClickEvents();
    addContactPageClickEvents();
    addContactPageFormValidation();
    addNewsletterFormValidation();
    addProjectSearchValidation();
    addProjectSimpleSearchValidation();

    if($j('#socialTarget').length > 0 && typeof SHARETHIS != undefined){
        var shareObject = SHARETHIS.addEntry({
            title:document.title
        }, {
            button:false
        });
        shareObject.attachButton($j('#socialTarget')[0]);
    }
    $j('#socialTarget').click(function(){
        return false;
    })

    // check if there is a google map in the page.
    if($j('#map_canvas').length > 0){
        initGoogleMap($j('#map_canvas'));
    }

    // check if there is a google map in the contact page.
    if($j('.googleMapWrapper').length > 0 && $j('#mapAttr').length > 0){
        initGoogleMap($j('.googleMapWrapper'));
    }

    // Add client side paging on MGGG overview page.
    if($j("#pagingItems").length > 0) {
        $j("#pagingItems").quickPager( {
            pageSize: translate("mgggbundle", "search.pagesize"),
            currentPage: 1,
            holder: ".pageNavwrapper",
            label_previous4: translate("mgggbundle", "search.previous"),
            label_next4: translate("mgggbundle", "search.next")
        });
        $j('#previouslink').hide();
        $j('#nextgrey').hide();
    }

    // Add client side paging on MGGG overview page.
    if($j("#logoutPagingItems").length > 0) {
        $j("#logoutPagingItems").quickPager( {
            pageSize: 2,
            currentPage: 1,
            holder: ".pageNavwrapper",
            label_previous4: translate("mgggbundle", "search.previous"),
            label_next4: translate("mgggbundle", "search.next")
        });
        $j('#previouslink').hide();
        $j('#nextgrey').hide();
        $j("#logoutPagingItems").removeClass('hidden');
    }

    // this needs to be called after the initialization of the social media button otherwise the sharethis events will not be captured.
    addAnalyticsEvents();

    // Add click event to the theme tabs.
    $j('#thTabs ul li a').each(function(skipIndex){
        $j(this).click(function(){
            setClassToSelection($j('#thTabs ul li a'), skipIndex, 'selected', true);
            setClassToSelection($j('div.tabContentWrapper'), skipIndex, 'hidden', false);
            return false;
        }
        );
    });

    // Add click event to the How Triodos acts tabs.
    $j('.actTabs .horizontalTabs ul li a').each(function(skipIndex){
        $j(this).click(function(){
            setClassToSelection($j('.actTabs .horizontalTabs ul li'), skipIndex, 'selected', true);
            setClassToSelection($j('.horizontalTabNav .edgedContainer'), skipIndex, 'hidden', false);
            return false;
        }
        );
    });

    $j("#productTabs li a").click(function() {
        getTabContent(this, $j(this)[0].href);
        return false;
    });

    if($j("#subsearchform").length > 0 || $j("#searchform").length > 0){
        defaultText();
    }

    $j(".kvmfield").bind("blur", checkEmpty );

    // Add click event to video demos.
    $j('.clickArea .video a').click(function(){
        playNew($j(this).find('span.hidden[name*=soparams]').text(), $j(this).find('span.hidden[name*=sovars]').text());
        $j('.clickArea .video.selected').removeClass('selected');
        $j(this).parent().addClass('selected');
        return false;
    });

    // ADMIN Module - "Mijn geld gaat goed" table
    if ( $j('#mgggTable').length > 0 && jQuery().tablesorter ) {
        var sortOrder = getUrlVars()["so"];
        var setOrder = new Boolean(true);
        if (sortOrder != null && sortOrder.length >= 1){
            // Take over the sort order submitted by client
            try{
                var myArray = sortOrder.split(",");
                if (myArray[0] != null && myArray[1] != null && myArray[2] != null && myArray[3] != null){
                    $j("#mgggTable").tablesorter( {
                        sortList: [[ parseInt(myArray[0]),parseInt(myArray[1])], [ parseInt(myArray[2]),parseInt(myArray[3])]],
                        widgets: ['zebra']
                    } );
                }else if (myArray[0] != null && myArray[1] != null){
                    $j("#mgggTable").tablesorter( {
                        sortList: [[ parseInt(myArray[0]),parseInt(myArray[1])]],
                        widgets: ['zebra']
                    } );
                }
                setOrder = false;
            }
            catch(err){
                setOrder = true;
            }
        }else{
            setOrder = true;
        }
        if (setOrder){
            // The default sort order (on  common name).
            $j("#mgggTable").tablesorter( {
                sortList: [[0,0]],
                widgets: ['zebra']
            } );
        }
        if($j("#pages").length > 0){
            $j("#mgggTable").tablesorterPager({
                container: $("#pager")
            });
        }
    }

    if($j('#moreOptions input[type=checkbox].supersector').length > 0){
        $j('#moreOptions input[type=checkbox].supersector').change(function(){
            if ($j(this).attr("checked")){
                $j(this).siblings('ul').find('input[type=checkbox].subsector').attr('checked', 'checked');
            }
            else {
                $j(this).siblings('ul').find('input[type=checkbox].subsector').removeAttr('checked');
            }
        });
        $j('#moreOptions input[type=checkbox].subsector').change(function(){
            if ($j(this).attr('checked')){
                var allChecked = true;
                $j(this).parent().siblings().each(function(index, element){
                    if(!$j(element).find('input[type=checkbox]').attr('checked')){
                        allChecked = false;
                    }
                });
                if(allChecked){
                    $j(this).parent().parent().parent().children('input[type=checkbox].supersector').attr('checked', 'checked');
                }
            }
            else {
                $j(this).parent().parent().parent().children('input[type=checkbox].supersector').removeAttr('checked');
            }
        });
        $j('#moreOptions input[type=checkbox].supersector').each(function(index, element){
            var allChecked = true;
            $j(element).siblings('ul').find('input[type=checkbox].subsector').each(function(index, element){
                if(!$j(element).attr('checked')){
                    allChecked = false;
                }
            });
            if(allChecked){
                $j(element).attr('checked', 'checked');
            }
        });
    }

    if($j('#projectAdmin').length > 0){
        if($j.browser.msie){
            if($j('input[name=selectBranch]').val() == 'true'){
                window.location.hash = 'branch';
            }
            else if($j('input[name=addLocation]').val() == 'true'){
                window.location.hash = 'location';
            }
        }
    }

});

/**
 * Function to use to get content via ajax.
 **/
function getTabContent(linkObj, requestUrl) {
    $j.ajax({
        url: requestUrl + "?view=tabOnly",
        success: function(data) {
            $j(".tabContentWrapper").html(data);
            $j(".tabs ul li .selected").removeClass("selected");
            $j(linkObj).addClass("selected");
            addLinkClasses();
            // update href of print page and save as pdf if they exist.
            if($j('.contentNav li.print a').length > 0){
                $j('.contentNav li.print a').attr('href', requestUrl + '?print=true');
            }
            if($j('.contentNav li.pdf a').length > 0){
                $j('.contentNav li.pdf a').click(function(){
                    $j(this).attr('href', '/CreatePDF' + "?ajaxUrl="+requestUrl);
                });
            }
        }
    });
}

/*
 * Adds a CSS class to the given selection of elements but remove that class at the given index. When the parameter "reversed"
 * is set to true then the exact opposite will be performed.
 */
function setClassToSelection(targetElements, skipIndex, className, reversed) {
    targetElements.each(function(idx) {
        if(skipIndex != idx ^ reversed) {
            $j(this).addClass(className);
        }
        else {
            $j(this).removeClass(className);
        }
    });
}

function translate(bundleName, propertyName) {    
    var response = "";
    $j.ajax({
        url: "/AjaxProcessor",
        data: ({
            action: 'resourceBundle',
            language: $j("meta[name=language]").attr("content"),
            country: $j("meta[name=country]").attr("content"),
            hostPrefix: $j("meta[name=hostPrefix]").attr("content"),
            property: propertyName,
            bundle: bundleName
        }),
        type: "POST",
        dataType: "text",
        async:false,
        success: function(data){
            response = data;
        }
    });
    return response;
}

/**
 * Function that adds a class extern to all external links (except links that have an image or span as child).
 *
 */
function addLinkClasses(){
    // add target blank to all external links
    $j('a').filter(function() {
        var target = $j(this).attr('target');
        if(typeof target != undefined && target != ''){
            return false;
        }
        var imageChild = jQuery('img', this);
        if(typeof imageChild != undefined && imageChild != '' && imageChild != null && imageChild.length > 0){
            return false;
        }
        var spanChild = jQuery('span', this);
        if(typeof spanChild != undefined && spanChild != '' && spanChild != null && spanChild.length > 0){
            return false;
        }
        return this.hostname && this.host && !(this.hostname == location.hostname || this.host == location.hostname);
    }).attr('target', '_blank');

    // the following types should be opened in a new window
    var newwindowDocs = [".pdf",".doc",".xls",".ppt",".docx",".xlsx",".pptx"];
    // add class newwindow to a specified types or if it has class newwindow.
    $j('a').filter(function() {
        var target = $j(this).attr('target');
        if(typeof target != undefined && target != ''){
            return false;
        }
        if($j(this).hasClass('extern')){
            return false;
        }
        if($j(this).hasClass('newwindow')){
            return true;
        }
        for(var i=0; i<newwindowDocs.length; i++){
            if(this.href.indexOf(newwindowDocs[i]) != -1){
                return true;
            }
        }
        return false;
    }).attr('target', '_blank');
}

function addCampaignClickEvents(){
    $j('.campaign ul.index li a').click(function(){
        var index = $j(this).attr('id').substring(4);
        if(index > 0){
            // update which image is visible (has class selected)
            $j(".campaign ul.campaigns li.selected").removeClass("selected");
            $j(".campaign ul.campaigns li:nth-child("+index+")").addClass("selected");
            // update the clicked button to show as selected
            $j(".campaign ul.index li a.selected").removeClass("selected");
            $j(this).addClass("selected");
        }
        return false;
    });
}

function addContactPageClickEvents(){
    var mapCentered = false;
    $j('#contactPageTabs ul li a').click(function(){
        // updated the selected for the tabs.
        var oldIndex = $j('.horizontalTabs ul li.selected').attr('id').substring(4);
        if(oldIndex > 0){
            $j('#contactPageTabs ul li.selected').removeClass('selected');
            $j(this).parent().addClass("selected");
        }
        // update selected form
        var newIndex = $j(this).parent().attr('id').substring(4);
        if(newIndex > 0){
            $j('.horizontalTabContentWrapper #form'+oldIndex).addClass('hidden');
            $j('.horizontalTabContentWrapper #form'+newIndex).removeClass('hidden');
        }

        // this is needed for firefox where the map is not completely loaded otherwise.
        if(!mapCentered && map != null){
            google.maps.event.trigger(map, 'resize');
            map.setCenter(initCenter);
            mapCentered = true;
        }
        return false;
    });
}

function addContactPageFormValidation(){
    if($j("#callbackForm").length > 0){
        $j("#callbackForm input[type=text]").each(function(index, element){
            if($j(element).attr("name") != 'sField'){
                initTextFields(element, "contactbundle", "contactCallback", true);
            }
        });

        $j("#callbackForm textarea").each(function(index, element){
            initTextFields(element, "contactbundle", "contactCallback", false);
        });

        initRadiobutton('callbackForm', 'emailExistingClient');

        initDropdown('contactbundle', 'callbackForm', 'sector');
        initDropdown('contactbundle', 'callbackForm', 'contactTime');
    }
    
    if($j("#emailForm").length > 0){
        $j("#emailForm input[type=text]").each(function(index, element){
            if($j(element).attr("name") != 'sField'){
                initTextFields(element, "contactbundle", "contactEmail", true);
            }
        });

        $j("#emailForm textarea").each(function(index, element){
            initTextFields(element, "contactbundle", "contactEmail", false);
        });

        initRadiobutton('emailForm', 'callbackExistingClient');
        initDropdown('contactbundle', 'emailForm', 'sector');
        initDropdown('contactbundle', 'emailForm', 'subject');
    }
}

function addNewsletterFormValidation(){
    if($j("#newsletterForm").length > 0){
        $j("#newsletterForm input[type=text]").each(function(index, element){
            if($j(element).attr("name") != 'sField'){
                initTextFields(element, "newsletterbundle", "newsletter");
            }
        });
        var errorMessage1 = translate("newsletterbundle", "error.newsletter.mandatory");
        // ^ means starts with.
        $j("#newsletterForm input[name^='newsletter']").change(function(){
            var selectedNewsletters = $j("#newsletterForm input[name^='newsletter']:checked").length;
            if(selectedNewsletters == 0){
                if($j('#checkboxes').attr('class') != 'message'){
                    $j('#checkboxes').addClass('message');
                    $j('#checkboxes').children(':last-child').after("<span class=\"messageHint\">"+errorMessage1+"</span>");
                }
            }
            else {
                $j('#checkboxes').removeClass('message');
                $j('#checkboxes').children('.messageHint').remove();
            }
        });
        initRadiobutton('newsletterForm', 'existingClient');
        initRadiobutton('newsletterForm', 'gender');
    }
}

function addProjectSearchValidation(){
    if($j("#projectSearchForm").length > 0){
        $j("#projectSearchForm input[type=text]").each(function(index, element){
            initTextFields(element, "projectsearchbundle", "projectSearch", true);
        });
    }
}

function addProjectSimpleSearchValidation(){
    if($j("#projectSimpleSearchForm").length > 0){
        $j("#projectSimpleSearchForm input[type=text]").each(function(index, element){
            var defaultMessage = translate("projectsearchbundle", $j(element).attr("id")+".default.text");
            if($j(element).val() == ""){
                $j(element).val(defaultMessage);
            }
            $j(element).focus(function(){
                if ($j(this).val() == defaultMessage){
                    $j(this).val("");
                }
            });
            $j(element).blur(function(){
                if ($j(this).val() == ""){
                    $j(this).val(defaultMessage);
                }
            });
        });
    }
}

function initDropdown(bundleName, formName, fieldName){
    $j("#"+formName+" #"+fieldName).blur(function(){
        var selected = $j("#"+formName+" #"+fieldName+" option:selected");
        if(selected != null && selected.val() != null && selected.val().substring(0, 6) == 'option'){
            removeErrorHighlight($j("#"+formName+" #"+fieldName)[0]);
        }
        else {
            var errorMessage = translate(bundleName, "error."+fieldName+".invalid");
            addErrorHighlight($j("#"+formName+" #"+fieldName)[0], errorMessage, 'true');
        }
    });
}

function initRadiobutton(formName, fieldName){
    $j("#"+formName+" #"+fieldName+" input[type='radio']").change(function(){
        var nbrSelected = $j("#"+formName+" input[name='"+fieldName+"']:checked").length;
        // a radio button cannot be deselected therefore only ncessary to remove message.
        if(nbrSelected == 1){
            removeErrorHighlight($j("#"+formName+" #"+fieldName)[0]);
        }
    });
}

function initTextFields(element, bundleName, formName, displayErrorImage){
    var elementName = $j(element).attr("name");
    var defaultMessage = translate(bundleName, $j(element).attr("name")+".default.text");
    if($j(element).val() == ""){
        $j(element).val(defaultMessage);
    }
    $j(element).focus(function(){
        if ($j(this).val() == defaultMessage){
            $j(this).val("");
        }
    });
    $j(element).blur(function(){
        if ($j(this).val() == ""){
            $j(this).val(defaultMessage);
        }
        else if($j(this).val() != defaultMessage){
            var errorMessage = translate(bundleName, "error."+elementName+".invalid");
            $j.post(
                '/ValidationProcessor',
                {
                    fieldName: elementName,
                    formName: formName,
                    value: $j(this).val()
                },
                function(validationResult){
                    if(validationResult == 'false'){
                        addErrorHighlight(element, errorMessage, displayErrorImage);
                    }
                    else {
                        removeErrorHighlight(element);
                    }
                }
                );
        }
    });
}

function addErrorHighlight(element, errorMessage, displayErrorImage){
    if($j(element).attr('type') == 'text' || element.tagName.toLowerCase() == 'select' || element.tagName.toLowerCase() == 'textarea'){
        $j(element).parent().addClass('message');
        if(displayErrorImage == 'true'){
            if($j(element).siblings('.messageVisual').length == 0){
                $j(element).after("<span class=\"messageVisual\"><img alt=\"\" src=\"/static/img/ic-false.gif\"></span>");
            }
        }
        if($j(element).siblings('.messageHint').length == 0){
            if($j(element).siblings('.messageVisual').length == 0){
                $j(element).after("<span class=\"messageHint\">"+errorMessage+"</span>");
            }
            else {
                $j(element).siblings('.messageVisual').after("<span class=\"messageHint\">"+errorMessage+"</span>");
            }
        }
    }
    else if($j(element).attr('type') == 'radio'){
        $j(element).parent().parent().parent().addClass('message');
    }
}

function removeErrorHighlight(element){
    if($j(element).attr('type') == 'text' || element.tagName.toLowerCase() == 'select' || element.tagName.toLowerCase() == 'textarea'){
        if($j(element).siblings('.messageVisual').length != 0){
            $j(element).siblings('.messageVisual').remove();
        }
        $j(element).parent().children('span.messageHint').remove();
        $j(element).parent().removeClass('message');
    }
    else {
        $j(element).removeClass('message');
        $j(element).children('span.messageHint').remove();
    }
}
var map = null;
var initCenter = null;

function initGoogleMap(targetDiv){
    // these are hidden variables which are writte out from the parsed body field.
    var latitude = parseFloat($j('#mapAttr #latitude').html());
    var longitude = parseFloat($j('#mapAttr #longitude').html());
    var mapTypeId = $j('#mapAttr #type').html();
    var zoomLevel = parseInt($j('#mapAttr #zoomLevel').html());
    var showMarker = $j('#mapAttr #showMarker').html();
    $j('#mapAttr').remove();

    if(targetDiv.length == 1){
        
        var initZoom;
        if (latitude && longitude && zoomLevel) {
            initCenter = new google.maps.LatLng(latitude, longitude);
            initZoom = parseInt(zoomLevel, 10);
        }

        if(mapTypeId === 'SATELLITE' || mapTypeId === 'G_SATELLITE_MAP'){
            mapTypeId = google.maps.MapTypeId.SATELLITE;
        }
        else if (mapTypeId === 'TERRAIN' || mapTypeId === 'G_PHYSICAL_MAP') {
            mapTypeId = google.maps.MapTypeId.TERRAIN;
        }
        else if (mapTypeId === 'HYBRID' || mapTypeId === 'G_HYBRID_MAP'){
            mapTypeId = google.maps.MapTypeId.HYBRID;
        }
        else {
            mapTypeId =  google.maps.MapTypeId.ROADMAP;
        }

        // init map
        map = new google.maps.Map(targetDiv[0], {
            center: initCenter,
            zoom: initZoom,
            mapTypeId: mapTypeId,
            streetViewControl: false
        });

        if(showMarker != null && showMarker != 'undefined' && showMarker.indexOf('true') == 0){
            new google.maps.Marker({
                position: initCenter,
                map: map
            });
        }
    }
}

function defaultText(){
    var defaultMessage = translate("resourcebundle", "search.box.default.text");
    var subDefaultMessage = translate("resourcebundle", "subsearch.box.default.text");
    if (defaultMessage != null ){
        $j(".defaultText").val(defaultMessage);
        $j(".defaultText").focus(function(srcc){
            if ($j(this).val() == defaultMessage){
                $j(this).val("");
            }
        });
        $j(".defaultText").blur(function(){
            if ($j(this).val() == ""){
                $j(this).val(defaultMessage);
            }
        });
    }
    if (subDefaultMessage != null ){
        $j(".subDefaultText").val(subDefaultMessage);
        $j(".subDefaultText").focus(function(srcc){
            if ($j(this).val() == subDefaultMessage){
                $j(this).val("");
            }
        });
        $j(".subDefaultText").blur(function(){
            if ($j(this).val() == ""){
                $j(this).val(subDefaultMessage);
            }
        });
    }
}

function setFocus(ref) {
    setTimeout(function () {
        ref.focus()
    }, 100);
}

function checkEmpty(){
    var theKey = $j(this).attr('id');
    var theName = $j(this).attr('id').substring(0, jQuery.inArray("_", theKey));
    if ($j(this).val() == ""){
        var fieldEmptyMess = translate("resourcebundle", "kvm.page.err.fieldEmpty");
        if (fieldEmptyMess == null || fieldEmptyMess == ''){
            fieldEmptyMess = "This field may not be empty, please supply a value.";
        }
        fieldEmptyMess = fieldEmptyMess.replace('[name]',theName);
        alert( fieldEmptyMess );
        setFocus($j(this));
    }
    return true;
}

/**
 * Sets the anchor just before the form is submitted.
 */
function setKVMFormAnchor(formName) {
    var formElement = $j('#form_' + formName);
    $j(formElement).attr("action", $j(formElement).attr("action") + "#anchor_" + formName);    
}

function checkAllFields(myForm){
    // Check other fields when a KeyValue form is submitted.

    var fieldEmptyMessage = translate("adminforms", "kvm.page.err.fieldEmpty");
    if (fieldEmptyMessage == null || fieldEmptyMessage == ''){
        fieldEmptyMessage = "This field may not be empty, please supply a value.";
    }


    var submitForm = true;
    // Loop trhough all input fields of this form
    $j(myForm).find('input').each(function(i){
        if (submitForm == true){
            // We still have not found a empty field (submitForm == true)
            try{
                if ( (this.name.indexOf("category") == -1) && (this.value != "") ){
                    // This field is not empty, check the other ones as well
                    var theFullKey = $j(this).attr('id');
                    var theKey = theFullKey.substring(jQuery.inArray("_", theFullKey), theFullKey.length); // the itemKey

                    if(theKey != null){
                        var myValue = "value" + theKey;
                        var myKey   = "key" + theKey;
                        var myDesc  = "description" + theKey;
                        $j(myForm).find('input').each(function(f){
                            if (submitForm == true && (this.name == myValue || this.name == myKey || this.name == myDesc)){
                                if (this.value == null || this.value == ""){
                                    submitForm = false; //console.debug("DO NOT submit the FORM");
                                    var theName = this.name.substring(0, jQuery.inArray("_", this.name));
                                    fieldEmptyMessage = fieldEmptyMessage.replace('[name]',theName);
                                    alert(fieldEmptyMessage);
                                    setFocus(this);
                                    return false;
                                }

                            }
                        });
                    }
                }
            }catch (err){
            //console.error("Error processing field : " + this.name + " = " +  this.value);
            }
        }

    });

    if (submitForm == true){
        $j(myForm).submit();
    }
    return submitForm;
}

var currentState = "NONE";
var previousState = "NONE";
var player = null;
function playerReady(thePlayer) {
    player = window.document[thePlayer.id];
    // the addlisteners should only be done for the player in the brandbox therefore this check.
    if($j('.brandBoxWrapper').length > 0){
        addListeners();
    }
}

function playNew(soParams, soVariables) {

    var so = new SWFObject('/static/swf/player-licensed-viral.swf','mpl','560','340','9');

    // Add params
    jQuery.each(soParams.split(','), function() {
        var param = this.split('|');
        so.addParam(param[0].trim(), param[1].trim());
    });

    // Add variables
    jQuery.each(soVariables.split(','), function() {
        var variable = this.split('|');
        so.addVariable(variable[0].trim(), variable[1].trim().replace(/\*/g,','));
    });

    so.write('mediaspace');
}

function addListeners() {
    if (player) {
        player.addModelListener("STATE", "stateListener");
    } else {
        setTimeout("addListeners()",100);
    }
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
    currentState = obj.newstate;
    previousState = obj.oldstate;

    if (currentState == "PLAYING" || currentState == "BUFFERING") {
        $j('.brandBoxWrapper').cycle('pause');
    }
    if ((currentState == "COMPLETED" || currentState == "IDLE")&&(previousState == "PLAYING")) {
        var sleepAfterMovie = $j('#sleepAfterMovie').html();
        if(sleepAfterMovie == null || sleepAfterMovie == '' || sleepAfterMovie <= 0){
            sleepAfterMovie = 300000;
        }
        
        // wait for 30 seconds so there is time to see the share this box
        setTimeout(function(){
            $j('.brandBoxWrapper').cycle('resume')
        },sleepAfterMovie);
    }
}


function addAnalyticsEvents(){
    
    jQuery('a').each(function(index, element){
        if(element.href != null && element.href.length > 0){
            
            // track external links
            if(element.hostname && element.host && !(element.hostname == location.hostname || element.host == location.hostname)
                && element.href.indexOf('mailto:') == -1){
                // this adds a click event and nothing happens with already existing events.
                jQuery(element).click(function(){
                    _gaq.push(['_trackPageview', '/ext/'+element.href.split('//')[1]]);
                });
            }
            else {
                // track internal download documents therefore this is in the else..
                for(var i=0; trackDocs != null && i<trackDocs.length; i++){
                    if(element.href.indexOf(trackDocs[i]) != -1){
                        var splitHref = element.href.split(location.hostname)[1];
                        // if the hostname contains port number make sure it is removed.
                        if(splitHref.substr(0,1) == ":"){
                            var slashIndex = splitHref.indexOf('/');
                            splitHref = splitHref.substr(slashIndex+1);
                        }
                        jQuery(element).click(function(){
                            _gaq.push(['_trackPageview', '/downloads/'+splitHref]);
                        });
                    }
                }
            }

            // track mailto: links
            if(element.href.indexOf('mailto:') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackPageview', '/mailto/'+element.href.split('mailto:')[1]]);
                });
            }

            // track clicks on product tabs as normal page views. The content is retrieved with an ajax call
            // and will otherwise not be counted.
            if(element.id != null && element.id.indexOf('producttab') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackPageview', element.href]);
                });
            }

            // track clicks on the brandbox tabs
            if(element.href.indexOf('boxtab=') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Brandbox tab click', element.href]);
                });
            }

            // track clicks on the theme block tabs
            if(element.href.indexOf('themetab=') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Theme block tab click', element.href]);
                });
            }

            // track clicks on the how triodos acts tabs
            if(element.href.indexOf('actstab=') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'How triodos acts tab click', element.href]);
                });
            }

            // track clicks on contact tabs
            if(element.id != null && element.id.indexOf('contacttab') != -1){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Contact tab click', element.href]);
                });
            }
            
            // track clicks on save as pdf (the parent li item has class pdf and class saveaspdf)
            if(jQuery(element).parent('li') != null && jQuery(element).parent('li').hasClass('saveaspdf')){
                jQuery(element).click(function(){
                    var pathname = window.location.pathname;
                    if(pathname.substring(pathname.length-1) == '/'){
                        pathname = pathname.substring(0, pathname.length-1);
                    }
                    var urlParts = pathname.split('/');
                    if(urlParts != null && urlParts.length > 0){
                        var pdfName = urlParts[urlParts.length-1] + '.pdf';
                    }
                    if(pdfName != '' && pdfName != '.pdf'){
                        _gaq.push(['_trackEvent', 'FormAction', 'Save as PDF', pdfName]);
                    }
                    else {
                        _gaq.push(['_trackEvent', 'FormAction', 'Save as PDF']);
                    }
                });
            }

            // track clicks on print this page
            if(jQuery(element).parent('li') != null && jQuery(element).parent('li').hasClass('print')){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'FormAction', 'Print this page']);
                });
            }

            // track clicks on social bookmarking
            if(jQuery(element).parent() != null && jQuery(element).parent().parent() != null && jQuery(element).parent().parent('li').hasClass('socialMedia')){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'FormAction', 'Social networks']);
                });
            }

            // track clicks on the links above the mggg map
            if(element.id == 'branchView'){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Mggg Map', 'Click view', 'Branch']);
                });
            }
            if(element.id == 'europeView'){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Mggg Map', 'Click view', 'Europe']);
                });
            }
            if(element.id == 'worldView'){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Mggg Map', 'Click view', 'World']);
                });
            }

            if(jQuery(element).hasClass('projectLink')){
                jQuery(element).click(function(){
                    _gaq.push(['_trackEvent', 'Mggg Search results', 'Click project link', jQuery(element).html()]);
                });
            }
            if($j('.mapMGGG').length > 0){
                if(element.id == 'nextlink'){
                    jQuery(element).click(function(){
                        _gaq.push(['_trackEvent', 'Mggg Search results', 'Browse paged results', 'Next']);
                    });
                }
                else if(element.id == 'previouslink'){
                    jQuery(element).click(function(){
                        _gaq.push(['_trackEvent', 'Mggg Search results', 'Browse paged results', 'Previous']);
                    });
                }
            }

            if(jQuery(element).hasClass('moreOptionsToggler')){
                jQuery(element).click(function(){
                    if(jQuery(element).hasClass('less')){
                        _gaq.push(['_trackEvent', 'Mggg Search input', 'Toggle advanced options', 'Open']);
                    }
                    else {
                        _gaq.push(['_trackEvent', 'Mggg Search input', 'Toggle advanced options', 'Close']);
                    }
                });
            }
        }
    });

}

/*******
 ** jFlow based contentFlow (productpage)
 *******/
var currentPage = 1;
var totalPages = 0;
var offset = 0;

var initJflow = function()
{
    if ($j("div#controller").length > 0){
        $j("div#controller").jFlow
        ({
            slides: "#slides",
            width: "300px",
            height: "360px",
            duration: 400,
            startPage: currentPage
        });
        totalPages = $j('#slides > .jFlowSlideContainer').length;
    }
}

function addPages(direction){

    if(currentPage == (totalPages - 2) || currentPage == 2){
        $j.post('/ProjectPaging',
        {
            maxResults: "150",
            offSet: offset + 8,
            varSubSelect:"otherProjects",
            varHeaders:"otherProjectsHeader",
            sectorIds: "",
            //nrBeforeAndAfter: "6",
            projectItemKey: $j('#projecItemKey').html(),
            branchItemKeys: $j('#branches').html(),
            lang: $j("meta[name=language]").attr("content"),
            country: $j("meta[name=country]").attr("content"),
            hostPrefix: $j("meta[name=hostPrefix]").attr("content"),
            numberItems: "24",
            direction: direction
        },
        function(data){
            if(data != null){
                // only add complete pages.
                var contentUpdated = false;
                for(var i=0; i <= data.length - 4; i = i+4){
                    addPage = $j("<div class=\"thumbOverview\">\n\
                                        <div class=\"row\">\n\
                                            <div class=\"first-child\">\n\
                                                <a class=\"thumb\" href=\"?projectId="+data[i].key+"\"><img src=\""+data[i].vis+"?imageManipulation=true&amp;compression=1&amp;maintainRatio=true&amp;pixelsY=89&amp;pixelsX=134&amp;fileFormat=2&amp;quality=3\" alt=\""+data[i].name+"\" /></a>\n\
                                                <a href=\"?projectId="+data[i].key+"\">"+data[i].nam+"</a>\n\
                                                <span>"+data[i].sec+"</span>\n\
                                            </div>\n\
                                            <div>\n\
                                                <a class=\"thumb\" href=\"?projectId="+data[i+1].key+"\"><img src=\""+data[i+1].vis+"?imageManipulation=true&amp;compression=1&amp;maintainRatio=true&amp;pixelsY=89&amp;pixelsX=134&amp;fileFormat=2&amp;quality=3\" alt=\""+data[i+1].name+"\" /></a>\n\
                                                <a href=\"?projectId="+data[i+1].key+"\">"+data[i+1].nam+"</a>\n\
                                                <span>"+data[i+1].sec+"</span>\n\
                                            </div>\n\
                                        </div>\n\
                                        <div class=\"row\">\n\
                                            <div class=\"first-child\">\n\
                                                <a class=\"thumb\" href=\"?projectId="+data[i+2].key+"\"><img src=\""+data[i+2].vis+"?imageManipulation=true&amp;compression=1&amp;maintainRatio=true&amp;pixelsY=89&amp;pixelsX=134&amp;fileFormat=2&amp;quality=3\" alt=\""+data[i+2].name+"\" /></a>\n\
                                                <a href=\"?projectId="+data[i+2].key+"\">"+data[i+2].nam+"</a>\n\
                                                <span>"+data[i+2].sec+"</span>\n\
                                            </div>\n\
                                            <div>\n\
                                                <a class=\"thumb\" href=\"?projectId="+data[i+3].key+"\"><img src=\""+data[i+3].vis+"?imageManipulation=true&amp;compression=1&amp;maintainRatio=true&amp;pixelsY=89&amp;pixelsX=134&amp;fileFormat=2&amp;quality=3\" alt=\""+data[i+3].name+"\" /></a>\n\
                                                <a href=\"?projectId="+data[i+3].key+"\">"+data[i+3].nam+"</a>\n\
                                                <span>"+data[i+3].sec+"</span>\n\
                                            </div>\n\
                                        </div>")[0];
                    if(direction == 'right'){
                        if(currentPage > 2){
                            $j('#slides > .jFlowSlideContainer:first-child').remove();
                            $j('#slides').append(addPage);
                            currentPage--;
                            contentUpdated = true;
                        }
                    }
                    else {
                        if(currentPage < (totalPages - 2)){
                            $j('#slides > .jFlowSlideContainer:last-child').remove();
                            $j('#slides').prepend(addPage);
                            currentPage++;
                            contentUpdated = true;
                        }
                    }
                }
                if(contentUpdated){
                    
                    setTimeout(function(){
                        initJflow();
                    }, 300);
                //initJflow();

                }
            }
        },
        'json'
        );
    }

}

$j(function()
{
    $j(".jFlowNext").click(function(event)
    {
        currentPage++;
        offset = offset + 4;
        addPages('right');
        
        return false;
    });

    $j(".jFlowPrev").click(function()
    {
        currentPage--;
        offset = offset - 4;
        addPages('left');

        return false;
    });

    // Fill the slides div with initial projects
    $j("#slides").html($j("#projects").html());
    // the displayed page should be in the middle of the search result so it is possible to scroll both left and right.
    currentPage = Math.ceil($j('#projects > .thumbOverview').length / 2);
    
    initJflow();

});

function getUrlVars(url)
{
    var vars = [], hash;
    var hashes;
    if(url === undefined) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    } else {
        hashes = url.slice(url.indexOf('?') + 1).split('&');
    }
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function setAddLocation(){
    $j('#addLocationSwitch').val('true');
}

function urlParam(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) {
        return 0;
    }
    return results[1] || 0;
}
