var hold_init = false;
/*
	script.js

* */
/*--------------------------------------------------------------------
 * javascript method: "pxToEm"
 * by:
   Scott Jehl (scott@filamentgroup.com)
   Maggie Wachs (maggie@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/
 *
 * Options:
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);

	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};

	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size.
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size.
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size)
		to get an accurate em value. */

	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };

	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};

/*--------------------------------------------------------------------
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article:
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

/**

	WNAS
	wilfred at wnas dot nl
	adapted to find the div's inside the container and set a height to them
**/
$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
//		console.log( $(this).children() );
		$(this).children().each(function(i){
		//	console.log( $(this).find('div').html() );
			if ($(this).find('div').height() > currentTallest) { currentTallest = $(this).find('div').height(); }
		});
		if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version > 7.0) {
		//	alert( currentTallest + ' = currentTallest');
			$(this).find('div').css({'height': currentTallest});
		}
		$(this).find('div').css({'min-height': currentTallest});
	});
	return this;
};





/**
 * @author info
 * Wilfred Nas
 * http://wnas.nl/
 * wilfred at wnas . nl
 * twitter.com/wnas
 *
 * Plugin to get a value from a className.
 *
 * Usage:
 * calling this:
 *  $('select').classValue('t');
 *  will give you the value you put in the className t:foo aka foo.
 *
 *  usefull if you have a few parameters you want to give to the js.
 */
(function($) {
    $.fn.extend({
        classValue : function(pf) {
			var cn = $(this).attr('class');
			var result = "";
			var test = new String(cn);
			var elementString = new String(pf);
			elementString = elementString + ":";
			var startpos = test.indexOf(elementString, 0);
			if (startpos >= 0){
			    test = test.substr(startpos, test.length);
			    if (test.indexOf(" ", 0) >= 0){
			        test = test.substr(elementString.length, test.indexOf(" ", 0) - elementString.length);
			    }
			    else{
			        test = test.substr(elementString.length, test.length - elementString.length);
			    }
			    result = test;
			}
			return result;
        }
    });
})(jQuery);

var CCV = function () {
	var init = function () {
		/*
			own stuff
		*/

		$('.webwinkel .results .more').click( function () {
			$(this).parent().toggleClass('short');
		});
		$('.home #main, .equalheights').equalHeights();

		/*
			 Autopopulate for search box...
				http://www.456bereastreet.com/archive/200710/autopopulating_text_input_fields_with_javascript/

				modified to use with jquery by wilfred nas
					http://wnas.nl/
					wilfred@wnas.nl
			 */
		var autoPopulate = {
			sInputClass:'autopopulate', // Class name for input elements to autopopulate
			init:function() {
				// Check for DOM support
				if (!document.getElementById || !document.createTextNode) {
					return;
				}
				// Find all input elements with the given className
				//var arrInputs = getElementsByClassName(document, 'input', autoPopulate.sInputClass);
				var arrInputs = jQuery( 'input.' + autoPopulate.sInputClass );
				var iInputs = arrInputs.length;
				var oInput;
				for (var i=0; i<iInputs; i++) {
					oInput = arrInputs[i];
					// Make sure it's a text input
					if (oInput.type != 'text') {
						continue;
					}
					// If value is empty and title is not, assign title to value
					if ((oInput.value == '') && (oInput.title != '')) {
						oInput.value = oInput.title;
						jQuery( oInput ).addClass('defaultInput');
					}
					// if we have been through this before.
					if ( oInput.value == oInput.title ){
						jQuery( oInput ).addClass('defaultInput');
					}
					// Add event handlers for focus and blur
					jQuery('input.autopopulate').focus(function() {
						// If value and title are equal on focus, clear value
						if (this.value == this.title) {
							this.value = '';
							this.select(); // Make input caret visible in IE
							jQuery(this).val('').removeClass('defaultInput');
						}
					});
					jQuery('input.autopopulate').blur(function() {
						// If the field is empty on blur, assign title to value
						if (!this.value.length) {
							this.value = this.title;
							jQuery(this).addClass('defaultInput');
						}
						else {
							if (this.value != this.title) { jQuery(this).removeClass('defaultInput'); }
						}
					});
				}
			}
		};

		autoPopulate.init();

		// faq stuff
		if ( $('.faq').length !== 0 ){
			// hide the answers of the faq.
			$('.faq dd:not(.selected)').hide();
			// toggle answers on click
			$('.faq dt').click( function () {
				$('.faq dd').hide();
				$(this).parent().find('dd, dt').removeClass('selected');
				$(this).addClass('selected').next().addClass('selected').slideDown('fast');
			});
		};

		// autocomplete stuff
		if ( $('.autoComplete').length !== 0 ){
			$("#autoComplete").autocomplete(themas, {
				minChars: 0,
				width: 200,
				scroll: false,
				scrollHeight : 400,
				matchContains: "word",
				autoFill: false,
				formatItem: function(row, i, max) {
					return  row.title + "<span>" + row.extra + "</span>" ;
				},
				formatMatch: function(row, i, max) {
					return row.title + " " + row.extra;
				},
				formatResult: function(row) {
					return row.title + " " + row.extra;
				}
			}).result(function(event, item) {
				location.href = item.url;
			});;
		};

		// toggle checkboxes from legend
		$('fieldset.mastercheckbox legend input[type=checkbox]').click( function (){
			var other = $(this).parent().parent().find('li input[type="checkbox"]');
			if ( this.checked ){
				$( other ).attr('checked','checked');
			}
			else {
				$( other ).attr('checked','');
			}
		});
		// toggle legend checkbox from within fieldset li's
		$('fieldset.mastercheckbox li input[type="checkbox"]').click( function () {
			var lcb = $(this).parent().parent().parent().find('legend input[type="checkbox"]')[0];
			if ( lcb.checked ){
				$( lcb ).attr('checked','');
			}
		});
		// remove line from webshop
		$('.webwinkel input.verwijder').click( function() { $(this).parent().parent().remove();return false;});
		$('#address').click( function () {
			$('#altAddress').toggleClass('show');
		});

		$('#agree').click( function () {
			$('td.verzenden').toggleClass('touched');
		});

		$('#confirm p:first-child').before('<button id="print">Ontvangstbevestiging afdrukken');
		$('#print').click( function () {
			window.print();
			return false;
		});

	};
	return {
		init: init
	};
}();
function trackMe(me) {
    try {
        me = $(me);
        link = me.attr('href');
        me = me.attr('href');
        me = me.replace('http://', '');
        var splitAt = me.indexOf('/');
        var path = me.substring(splitAt, me.length);
        //alert('tracking: ' + path)
        pageTracker._trackPageview(path);
        if ($.browser.msie && $.browser.version == "8.0") {
        	setTimeout('window.open("' + link + '", "_self")', 100);
        } else {
        	setTimeout('window.open("' + link + '")', 100)
        }
    } catch(e) {
    }

}

function isEmpty(string) {
    if (string == null) {
        return true;
    }
    if (string.length == 0) {
        return true;
    }
    return false;
}

function requestAssetInfo() {
    $("div.linkBlock a.asset").each(function() {
        var a = $(this);
        var href = a.attr("href");
        $.ajax({ url : siteUrl,
            data : {src : href},
            success : function(xml) {
                var size = $(xml).find("size").text();
                var unit = $(xml).find("unit").text();
                var typeLabel = $(xml).find("typelabel").text();
                var mimeType = $(xml).find("mimetype").text();
                if (!isEmpty(mimeType)) {
                    mimeType = mimeType.replace(/[^\w]/g, "");
                    if (/^image/i.test(mimeType)) {
                        a.addClass("image");
                    }
                    if (/^application/i.test(mimeType)) {
                        a.addClass("application");
                    }
                    if (/^audio/i.test(mimeType)) {
                        a.addClass("audio");
                    }
                    if (/^text/i.test(mimeType)) {
                        a.addClass("text");
                    }
                    if (/^video/i.test(mimeType)) {
                        a.addClass("video");
                    }
                    a.addClass(mimeType);
                }
                if (!isEmpty(typeLabel) && !isEmpty(size)) {
                    a.after("<span class=\"assetType\">(" + typeLabel + ", " + size + " " + unit + ")</span>");
                }
            }
        });
    });
}

$(document).ready(
    function() {
    	// internal links should open in the same window for IE8:
    	if ($.browser.msie && $.browser.version == "8.0") {
    		$("a[href^=/]").attr("target", "_self");
    		// open internal links written as external links within self
            $("a[href^='http://www.hetccv.nl']").attr('target', '_self');
    		// open external links within self
            $("a[href^='http://']").attr('target', '_self');
    	}
    	
        // all binary links start in a new window, but call to trackMe to include google analytics:
        $("a[href*=.pdf], a[href*=.doc], a[href*=.ppt]").attr("target", "_self").attr("onClick", "trackMe(this); return false;");

        // add size and document type information to asset links
        requestAssetInfo();

        $("img[alt!='']").each(function() {
            $(this).attr("title", $(this).attr("alt")); 
        });

        if (hold_init) {
            CCV.init();
        }
    }
);

