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 = indi.utils.getUrlVars()[oscParameterName];
        if(typeof oscParameterNameValue !== "undefined") {
            _gaq.push(['_setCustomVar', 1, 'On site campaign', oscParameterNameValue, 2]);
        }
        _gaq.push(['_trackPageview']);
        if(typeof trackLoadTime !== "undefined" && trackLoadTime){
            _gaq.push(['_trackPageLoadTime']);
        }
    }

    addLinkClasses();
    addCampaignClickEvents();
    addContactPageClickEvents();
    addContactPageFormValidation();
    addCreditCardFormValidation();
    addNewsletterFormValidation();
    addProjectSimpleSearchValidation();
    addDropDownEvents();
    initProjectPage();
    initCcForm();
    initMail2FriendForm();
    initFaqDetails();

    // 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'));
    }

    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() {
        if(!$j(this).parent().hasClass("plus")){
            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;
    });

    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';
            }
        }
    }
    
    if($j('.ajax').length > 0){
        $j('.ajax').click(function(){            
            if($j(this).attr("id") === 'projectExport'){
                $j.ajax({
                    url: "/ProjectExport",
                    type: "POST",
                    data: ({step: "1",
                            sField: "",
                            lang: $j("meta[name=language]").attr("content"),
                            country: $j("meta[name=country]").attr("content"),
                            hostPrefix: $j("meta[name=hostPrefix]").attr("content")                                
                           })
                });
                // disable the button
                $j(this).attr("disabled", "disabled");
                $j(this).parent().after("<div class=\"richText topmargin\">"+translate("resourcebundle", "mggg.admin.export.started.text")+"</div>");
            }   
            return false;
        });
    }

});

function initFaqDetails(){
    
    $j("a.questionQualityYes").bind("click.feedback", function(){
        registerFaqAnswer("yes");
    });
    $j("a.questionQualityNo").bind("click.feedback", function(){
        registerFaqAnswer("no");
    });
}

function registerFaqAnswer(clickValue){
    $j.ajax({
        url: "/AjaxProcessor",
        data: ({
            action: 'faqAnswered',
            language: $j("meta[name=language]").attr("content"),
            country: $j("meta[name=country]").attr("content"),
            hostPrefix: $j("meta[name=hostPrefix]").attr("content"),
            id: urlParam("faqId"),
            aId: $j("#aId").html(),
            answer: clickValue,
            itemId: $j("meta[name=itemId]").attr("content")
        }),
        type: "POST",
        dataType: "text",
        success: function(data){
            if(data !== '' && data !== 'null'){
                $j(".questionQuality").append("<span class=\"response "+clickValue+"\">"+data+"</span>");
                $j(".questionQuality"+clickValue.charAt(0).toUpperCase() + clickValue.slice(1)).append("<span class=\"arrowBorder\"></span><span class=\"arrow\"></span>");
            }
            $j("a.questionQualityYes").unbind("click.feedback");
            $j("a.questionQualityNo").unbind("click.feedback");
        }
    });
    return false;
}

function initMail2FriendForm(){
    if($j("#email2FriendForm").length > 0){
        $j("#email2FriendForm input[type=text]").each(function(index, element){
            if($j(element).attr("name") !== 'sField'){
                initTextFields(element, "resourcebundle", "mail2Friend", false);
            }
        });
    }
}

function initCcForm(){
    if($j(".helpIconImg").length > 0){
        $j(".helpIconImg").mouseenter(function(){
            $j(this).siblings(".helpIconInfo").removeClass("hidden");
        }).mouseleave(function(){
            $j(this).siblings(".helpIconInfo").addClass("hidden");
        });
    }
}

function initProjectPage(){
    // only applicable for the mggg project pages
    if($j(".projectLocation #projectSearchForm").length > 0){
        triodos.mggg.initSearchForm();
        $j(".browse").live('click.projectLink', function(){
            triodos.mggg.addClientSideParam(this);
        });
    }
}

/**
 * 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");
            if($j(linkObj).parent().hasClass("plusItem")){
                $j(linkObj).parent().parent().siblings().addClass("selected");
            }
            $j(linkObj).addClass("selected");
            addLinkClasses();
            // update href of print page an console.info(linkObj);d 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+"&pdfTitle="+escape(jQuery(linkObj).find('span').html()));
                });
            }
        }
    });
}

/*
 * 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;
        }
        var i;
        for(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 addCreditCardFormValidation(){
    if($j("#creditCardForm").length > 0){
        $j("#creditCardForm input[type=text]").each(function(index, element){
            if($j(element).attr("name") !== 'sField'){
                initTextFields(element, "creditcardbundle", "creditCard", true);
            }
        });
    }
}

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' &&
                $j(element).attr("name") !== 'phoneNumber'){
                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 addProjectSimpleSearchValidation(){
    if($j("#projectSimpleSearchForm").length > 0){
        $j("#projectSimpleSearchForm input[type=text]").each(function(index, element){
            var defaultMessage = translate("mgggbundle", $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, elementName+".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);
                    }
                }
                );
        }
    });
}

/**
 * Class text1 is specific for the credit card form. The other forms are all the same.
 **/
function addErrorHighlight(element, errorMessage, displayErrorImage){
    if($j(element).attr('type') === 'text' || element.tagName.toLowerCase() === 'select' || element.tagName.toLowerCase() === 'textarea'){
        var errorClass = 'message';
        if($j(element).hasClass('text1')){
            errorClass = 'messages';
        }
        $j(element).parent().addClass(errorClass);
        if(displayErrorImage){
            if($j(element).siblings('.messageVisual').length === 0){
                var imgErrorClass = '';
                if($j(element).hasClass('text1')){
                    imgErrorClass =  ' class=\"errorsImg\"';
                }
                $j(element).after("<span class=\"messageVisual\"><img"+imgErrorClass+" alt=\"\" src=\"/static/img/ic-false.gif\"></span>");
            }
        }
        if($j(element).siblings('.messageHint').length === 0){
            if($j(element).siblings('.messageVisual').length === 0){
                $j(element).parent().children(":last").after("<span class=\"messageHint\">"+errorMessage+"</span>");
            }
            else {
                $j(element).siblings('.messageVisual').after("<span class=\"messageHint\">"+errorMessage+"</span>");
            }
        }
        else if($j(element).siblings('.messageHint').html() !== errorMessage){
            $j(element).siblings('.messageHint').html(errorMessage);
        }
    }
    else if($j(element).attr('type') === 'radio'){
        $j(element).parent().parent().parent().addClass('message');
    }
}

/**
 * The message class is used in all normal forms while messages only is used in the
 * credit card form
 **/ 
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();
        if($j(element).hasClass('text1')){
            $j(element).parent().removeClass('messages');
        }
        else {
            $j(element).parent().removeClass('message');
        }
    }
    else {
        if($j(element).hasClass('text1')){
            $j(element).removeClass('messages');
        }
        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(), 10);
    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(){
    // get the values from the form instead of making another request.
    var defaultMessage = $j("#querytext").attr("title");
    var subDefaultMessage = $j(".subDefaultText").attr("title");
    if (defaultMessage !== null){
        $j(".defaultText").val(defaultMessage);
        $j(".defaultText").focus(function(src){
            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(x,soParam) {
        var param = soParam.split('|');
        so.addParam(jQuery.trim(param[0]), jQuery.trim(param[1]));
    });

    // Add variables
    jQuery.each(soVariables.split(','), function(y,vari) {
        var variable = vari.split('|');
        so.addVariable(jQuery.trim(variable[0]), jQuery.trim(variable[1]).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") {
        brandboxChangeState('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(){
            brandboxChangeState('resume');
        },sleepAfterMovie);
    }
}


function addAnalyticsEvents(){

    if(typeof _gaq !== "undefined"){
        // add events for the brandbox
        if($j("#navBrandBox").length > 0){
            $j("#navBrandBox a").click(function(){
                _gaq.push(['_trackEvent', 'Brandbox tab click', $j(this).attr("href")]);
            });
            $j("#navBrandBox li").mouseover(function(){
                _gaq.push(['_trackEvent', 'Brandbox tab mouseover', $j(this).children(0).html()]);
            });
            $j(".brandBoxWrapper .bbLink").click(function(){
                _gaq.push(['_trackEvent', 'Brandbox left link click', $j(this).attr("href")]);
            });
            $j(".actions a").click(function(){
                _gaq.push(['_trackEvent', 'Brandbox action click', $j(this).hasClass("pause") ? "pause" : "resume"]);
            });
            $j(".brandBoxWrapper a img").click(function(){
                _gaq.push(['_trackEvent', 'Brandbox image link click', $j(this).attr("src")]);
            });
        }
    
        jQuery("span[class^='st_']").click(function(){
            _gaq.push(['_trackEvent', 'FormAction', 'Social networks']);
        });

        jQuery("#voteForm").submit(function(){
            _gaq.push(['_trackEvent', 'Vote button click', $j(this).find("#campaignId").val(), $j(this).find("#companyId").val()]);
        });
                
        jQuery(".questionQualityYes").bind("click.analytics", function(){
            _gaq.push(['_trackEvent', 'FAQ', 'Yes click', $j("meta[name=title]").attr("content")]);
        });
        jQuery(".questionQualityNo").bind("click.analytics", function(){
            _gaq.push(['_trackEvent', 'FAQ', 'No click', $j("meta[name=title]").attr("content")]);
        });
        
        // class solution is set on the title of the faq answer
        if(jQuery(".solution").length > 0){
            var faqId = indi.utils.getUrlVars()['faqId'];
            if(typeof faqId !== "undefined" && faqId !== ''){
                _gaq.push(['_trackEvent', 'FAQ', 'Open FAQ', $j("meta[name=title]").attr("content")]);
            }
        }
        
        jQuery('a').each(function(index, element){
            if(element.href !== null && element.href.length > 0){
                var lang = $j("meta[name=language]").attr("content");
                // 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', '/'+lang+'/ext/'+element.href.split('//')[1]]);
                    });
                }
                else {
                    // track internal download documents therefore this is in the else..
                    var i;
                    for(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', '/'+lang+'/downloads/'+splitHref]);
                            });
                        }
                    }
                }

                // track mailto: links
                if(element.href.indexOf('mailto:') !== -1){
                    jQuery(element).click(function(){
                        _gaq.push(['_trackPageview', '/'+lang+'/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 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('/');
                        var pdfName = "";
                        if(urlParts !== null && urlParts.length > 0){
                            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']);
                    });
                }
            }
        });
    }
}

/*******
 ** 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;
                var i;
                for(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();

});

if (typeof indi === 'undefined') {
    var indi = {};
}

indi.utils = {
    getUrlVars: function (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;
}

function addDropDownEvents(){
    $j('#gotoSelect').click(function(){
        $j('#redirectForm').change(function(){
            $j(this).submit();
        });
    });
}
