function addToQs(name, val) {
	if (val != "") {
		return name + "=" + encodeURIComponent(val) + "&";
	}
	return "";
}

// Returns the background position given the center position. 
function calculatePosition(center) {
    var windoww = $(window).width();
    if (windoww > 1600) windoww = 1600; // max width we aim for.
    return -(center - (windoww / 2));
}

function initializebackground() {

    var offset = mpos;
    var pageclass = $("body").attr("class");
    if (pageclass.indexOf("knowledge") > -1) {
        offset = rpos;
    }
    if (pageclass.indexOf("news_and_events") > -1) {
        offset = lpos;
    }

    // Now scroll the body background-position to the place.
    var newpos = calculatePosition(offset);
    $("body").stop().animate({
        backgroundPosition: newpos + "px 0px"
    }, 0);

    //alert(" Width: " + windoww + " Scroll to " + newpos);
}


$(function() {
    $(".removeDefaultInputValue").removeDefaultInputValue();
    $(".inputEnterKey").checkInputEnterKey();
    $(".jshidden").removeClass("jshidden");
    $(".jshidewhenactive").removeClass("jshidewhenactive").addClass("hidden");
    $("#tabs").tabs();
    $("a.external").click(function() {
        this.target = "_blank";
    });

    $('a.flickrimage').cluetip({
        splitTitle: '|', // use the invoking element's title attribute to populate the clueTip...
        showTitle: true, // hide the clueTip's heading
        dropShadow: false,
        width: 260,
        topOffset: 0,
        leftOffset: 5,
        hoverIntent: {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        }

    });

    // Gray images are to be switched to color when hovering, both over the image itself, but also over the rest of the "article".
    // To use, place the gray image url in the img attr. "rev" and the color url in the "rev". Also set the image id.
    // On all elements that need to trigger the toggle,
    // set the class to "toggleImage" and set the "rel" to the image id.
    // TRA 2009.11.19  Ps: Remove this comment on deploy to prod. to reduce footprint. :-)
    $(".toggleImage").hover(
      function() {
          var imgid = $(this).attr("rel");
          var color = $("#" + imgid).attr("rel");
          $("#" + imgid).attr("src", color);
      },
      function() {
          var imgid = $(this).attr("rel");
          var gray = $("#" + imgid).attr("rev");
          $("#" + imgid).attr("src", gray);
      }
    );
    $("img.toggleMe").hover(
      function() {
          //var imgid = $(this).attr("id");
          var color = $(this).attr("rel");
          $(this).attr("src", color);
      },
      function() {
          //var imgid = $(this).attr("rel");
          var gray = $(this).attr("rev");
          $(this).attr("src", gray);
      }
    );

      $("#search").bind("keypress", function(e) {
      	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
      	if (key == 13) {
      		e.preventDefault();
      		$("#btnGlobalSearch").click();
      	}
      })

    $(window).resize(function() {
        var windoww = $(this).width();
        if (windoww > 1600) windoww = 1600; // max width we aim for.
        var offset = mpos;
        var pageclass = $("body").attr("class");
        var bodywidth = $("body").width();
        if (pageclass.indexOf("knowledge") > -1) {
            offset = rpos;
        }
        if (pageclass.indexOf("news_and_events") > -1) {
            offset = lpos;
        }

        //alert(" o:1000 w:1000 " + calculatePosition(1000));
        //alert(" o:2000 w:1000 " + calculatePosition(2000));
        // Now scroll the body background-position to the place.
        var newpos = calculatePosition(offset);
        $("body").stop().animate({
            backgroundPosition: newpos + "px 0px"
        }, 500);

        //alert(" Width: " + windoww + " Scroll to " + newpos);
    });



});

/* ADDTHIS BUTTON BEGIN */
var addthisScript = (("https:" == document.location.protocol) ? "https://s7.addthis.com/" : "http://s7.addthis.com/");
document.write(unescape("%3Cscript src='" + addthisScript + "js/250/addthis_widget.js' type='text/javascript'%3E%3C/script%3E"));


var addthis_config = {
	username: "cphcleantech",
	ui_header_color: "#ffffff",
	ui_header_background: "#2E5A8C",
	ui_language: "en",
	ui_offset_top: 5,
	ui_offset_left: 0,
	services_compact: "email, linkedin, facebook, twitter, favorites, more",
    services_exclude: ""
   };

   /*
   send mail
linkedIn
facebook
twitter
favoriter
   */

//var addthis_localize = {
//	share_caption: "Del siden"
//}; 

/* ADDTHIS BUTTON END */

; (function($) {

	$.fn.checkInputEnterKey = function() {

		$(this).bind("keypress", function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			if (key == 13) {
				e.preventDefault();
				var parentFieldset = $(e.target).parents("fieldset").find("input[type=submit]").click();
			}
		})
		return this;
	};

	$.fn.extend({
		removeDefaultInputValue: function() {
			return this.each(function() {
				new $.RemoveDefaultInputValueMethod(this);
			});
		}
	});

	$.RemoveDefaultInputValueMethod = function(input) {
		var $input = $(input);

		$("form").submit(function() {
			if ($input.val() == $input.attr("title")) {
				$input.val("");
			}
			return true;
		});

		$input.bind("focus", function(event) {
			if ($input.val() == $input.attr("title")) {
				$input.val("");
			}
		}).bind("blur", function(event) {
			if ($input.val() == "") {
				$input.val($input.attr("title"));
			}
		});

	};

})(jQuery);



/* QUICKPOLL BEGIN */
function AddVote(id, pageid) {
    var selectedValue = $("input[name='poll" + id + "']:checked").val();
    if (selectedValue == null)
        return false;

    $.ajax({
        type: "POST",
        url: "/FemtenNulOtte/COP/QuickPollVote.axd",
        data: "poll=" + id + "&pageid=" + pageid + "&vote=" + encodeURIComponent(selectedValue),
        success: function(html) {
            if (html == null || html == '')
                return;
            $("#pollContainer" + id).html(html);
        }
    });
}

/* ImageSwap */
function SetImageSrc(imageId, imageSrc) {
	var imageObj = $("#" + imageId);
	if (imageObj) {
		imageObj.attr("src", imageSrc);
	}
}

/* QUICKPOLL END */



/* EventArchive BEGIN */
function SetFilterCheckboxes(chkBox, classSelector)
{
    $("." + classSelector).attr('checked', chkBox.checked);    
}
/* EventArchive END */


/* Form validation START */
function ValidateForm(containerId) {
    var success = true;
    var message = 'Please fill out the following fields:\n';
    //validateMembersignonIndustry
    var membersignonIndustryFields = $("#" + containerId).find('.validateMembersignonIndustry');
    if (membersignonIndustryFields != null && membersignonIndustryFields.length > 0) {
        var field = membersignonIndustryFields[0];
        var result = ValidateMembersignonIndustry(field, containerId);
        if (result != '')
            message += '&raquo; '+ result;
    }

    //validateNotEmpty 
    var notEmptyFields = $("#" + containerId).find('.validateNotEmpty');
    if (notEmptyFields != null && notEmptyFields.length > 0) {
        for (i = 0; i < notEmptyFields.length; i++) {
            var field = notEmptyFields[i];
            if (!ValidateNotEmpty(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; '+label;
            }
        }
    }

    //validateEmail  
    var emailFields = $("#" + containerId).find('.validateEmail');
    if (emailFields != null && emailFields.length > 0) {
        for (i = 0; i < emailFields.length; i++) {
            var field = emailFields[i];
            if (!ValidateEmail(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; '+label;
            }
        }
    }

    

	//validateMustbeChecked
    var mustBeCheckedFields = $("#" + containerId).find('.validateMustbeChecked');
    if (mustBeCheckedFields != null && mustBeCheckedFields.length > 0)     
	{
        for (i = 0; i < mustBeCheckedFields.length; i++) {
            var field = mustBeCheckedFields[i];
            if (!ValidateMustBeChecked(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; ' + label;
            }
        }           		
	}
    
    //validateIfCheckedThenEmail
	var ifCheckedThenEmailFields = $("#" + containerId).find('.validateIfCheckedThenEmail');
    if (ifCheckedThenEmailFields != null && ifCheckedThenEmailFields.length > 0) 
	{
        for (i = 0; i < ifCheckedThenEmailFields.length; i++) {
            var field = ifCheckedThenEmailFields[i];
            var resultMsg = ValidateIfCheckedThenEmail(field, containerId);
			if(resultMsg != '')
			{
				success = false;
				message += "&raquo; "+resultMsg;
			}
        }           		
	}

	if (!success) {
	    // Emit error to a div with id = containerId + '_errors' - else to an alert.
	    if ($("#" + containerId + '_errors').is("div")) {
	        message = message.replace(/&raquo;/g, "<br />&raquo; ");
	        $("#" + containerId + '_errors').html(message);
	    }
	    else {
	        message = message.replace(/&raquo;/g, "\n ");
	        alert(message);
	    }
        return false;
    }    
    return true;
}

function ValidationGetLabel(inputId, containerId) {
    var label = $("#" + containerId).find("label[for=" + inputId + "]");
    if (label != null && label.length > 0) {
        return label.text();
    }
    return 'Field with id: ' + inputId;
}

function ValidateGetElementType(element)
{
    var elementType = element.tagName.toLowerCase();    
    if (elementType == 'input') {
        elementType = element.type.toLowerCase();
    }
    return elementType;
}

function ValidateGetValue(element) {
    var elementType = ValidateGetElementType(element);
    var value = '';
    switch (elementType) {
        case 'text':
            value = element.value;
            break;
        case 'select':            
            return element.options[element.selectedIndex].value;
            break;
         case 'checkbox':
         case 'radio':
            value = (element.checked)?'1':'0';
            break;
    };
    return value;
}

function ValidateNotEmpty(element) {
    var value = ValidateGetValue(element);    
    if (value == null || value == '' || element.title == value)  // also test for title - the default value of some text fields /TRA
        return false;
    return true;
}



function ValidateEmail(element) {
    var value = ValidateGetValue(element);
    var emailChk = new RegExp("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$");
    return (value.match(emailChk) != null);    
}

function ValidateMustBeChecked(element)
{
	var value = ValidateGetValue(element);
	if(value == '1')
		return true;
	return false;	
}

// requires that <input .... ref="emailFieldId"/>
function ValidateIfCheckedThenEmail(element, containerId)
{
    if (ValidateMustBeChecked(element)) {
        var emailFieldId = $(element).attr("ref");
        if (emailFieldId != null && emailFieldId != '') {
            var emailField = document.getElementById(emailFieldId);
            if(emailField != null) {
                if (!ValidateEmail(emailField)) {
                    var label = ValidationGetLabel(emailFieldId, containerId);
                    return label;
                }
            }
        }
    }
    return '';
}

function ValidateMembersignonIndustry(element, containerId) {    
    var checkboxes = $(element).find('.form_checkbox');
    var oneChecked = false;
    var otherChecked = false;
    for (var i = 0; i < checkboxes.length; i++) {
        var chkBox = checkboxes[i];
        if (chkBox.checked) {
            oneChecked = true;
            if (chkBox.id == 'chkOther')
                otherChecked = true;
        }
    }

    if (!oneChecked)
        return "Industry: ";
    if (otherChecked) {
        var otherCommentBox = document.getElementById('txtOtherComment');  //$("#txtOtherComment");
        if (!ValidateNotEmpty(otherCommentBox)) {
            return ValidationGetLabel(otherCommentBox.id, containerId) + " (Industry)";
        }
    }
    return '';
}

/* Form validation END */

/* Event form validation START */
function ValidateFormEvent(containerId) {
    var success = true;
    var message = 'Disse felter skal udfyldes:\n';
    //validateMembersignonIndustry
    var membersignonIndustryFields = $("#" + containerId).find('.validateMembersignonIndustry');
    if (membersignonIndustryFields != null && membersignonIndustryFields.length > 0) {
        var field = membersignonIndustryFields[0];
        var result = ValidateMembersignonIndustry(field, containerId);
        if (result != '')
            message += '&raquo; ' + result;
    }

    //validateNotEmpty 
    var notEmptyFields = $("#" + containerId).find('.validateNotEmpty');
    if (notEmptyFields != null && notEmptyFields.length > 0) {
        for (i = 0; i < notEmptyFields.length; i++) {
            var field = notEmptyFields[i];
            if (!ValidateNotEmpty(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; ' + label;
            }
        }
    }

    //validateEmail  
    var emailFields = $("#" + containerId).find('.validateEmail');
    if (emailFields != null && emailFields.length > 0) {
        for (i = 0; i < emailFields.length; i++) {
            var field = emailFields[i];
            if (!ValidateEmail(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; ' + label;
            }
        }
    }



    //validateMustbeChecked
    var mustBeCheckedFields = $("#" + containerId).find('.validateMustbeChecked');
    if (mustBeCheckedFields != null && mustBeCheckedFields.length > 0) {
        for (i = 0; i < mustBeCheckedFields.length; i++) {
            var field = mustBeCheckedFields[i];
            if (!ValidateMustBeChecked(field)) {
                success = false;
                var label = ValidationGetLabel(field.id, containerId);
                message += '&raquo; ' + label;
            }
        }
    }

    //validateIfCheckedThenEmail
    var ifCheckedThenEmailFields = $("#" + containerId).find('.validateIfCheckedThenEmail');
    if (ifCheckedThenEmailFields != null && ifCheckedThenEmailFields.length > 0) {
        for (i = 0; i < ifCheckedThenEmailFields.length; i++) {
            var field = ifCheckedThenEmailFields[i];
            var resultMsg = ValidateIfCheckedThenEmail(field, containerId);
            if (resultMsg != '') {
                success = false;
                message += "&raquo; " + resultMsg;
            }
        }
    }

    if (!success) {
        // Emit error to a div with id = containerId + '_errors' - else to an alert.
        if ($("#" + containerId + '_errors').is("div")) {
            message = message.replace(/&raquo;/g, "<br />&raquo; ");
            $("#" + containerId + '_errors').html(message);
        }
        else {
            message = message.replace(/&raquo;/g, "\n ");
            alert(message);
        }
        return false;
    }
    return true;
}
/* Event form validation END */