
$(document).ready(function() {
	webappPath = '';
	pathArray = new Array();
	pathArray = window.location.pathname.split( '/' );
	if (pathArray.length >= 3)  {
	len = pathArray.length - 3
	pathArray.length = len;
	webappPath = pathArray.join('/');
	}
    //alert(webappPath);
	var swfu;
	
	$.ajaxSetup ({
		cache: false
	});
	
	//mainmenu();
	//build menu with ID="myjquerymenu" on page:
	jquerycssmenu.buildmenu("myjquerymenu");
	$(".lidmaatschappen").show();
	memberHover();

	initLijstItems();
	showWerkzaamheid(0);
	initWorkLogoPopup();
	if ( $("#pipefitterSlides").length ) {
		initPipefitterSlidesPopup();
	}
	if ($(".offerformtemplate").length) {
		initOfferUpload();
		initCaptchaReloadAndPrint();
	}
	showSite();

    $('.slideshow').show();
    $('.slideshow').cycle({
		fx: 'fade',
        timeout: 500,
        speed: 750,
        random: 1        
	});
	
	if ($('#CmsPageAddForm').length) {
		$( '#CmsPageAddForm' ).submit(function() {
		  return submitForm('CmsPageAddForm');		  
		});
	}
	
	if ($("#CmsPageCityId").length > 0 && $("#CmsPageZip").length > 0) {
		$("#CmsPageCityId").bind('change', function() {
			$("#CmsPageZip").val("");
		});
	}
	
	$(".lidmaatschappen").removeAttr('style');
    
});

function initCaptchaReloadAndPrint() {
	$('#CaptchaImageReload').live('click', function(){
    	var randomnumber=Math.floor(Math.random()*11);	
    	$("#CaptchaImage").attr('src', webappPath + '/mail/captcha?x=' + randomnumber);
		return false;
	});
	
	$('#PrintOfferPage').live('click', function(){
    	$("#templatetext_right").printArea({mode: "popup", popClose: false, popWd: 520});
		return false;
	});
	
}

function initWorkLogoPopup() {
	
	if ($('#worklogoslideshow').length > 0) {
		$('#worklogoslideshow').cycle('destroy');
	}
	$("#werklogos .slidewerklogo").each(function(i,e){
		addSlideClickHandlerToWorkLogos(i,e);		
	});
	
	$("#werklogosmenu .menuslidewerklogo").each(function(i,e){
		addClickHandler4SlidesTo(".menulinkslidewerklogo", i,e);
	});
	
	$("#topbarclosebutton").live('click', function(){
		$('#worklogoslideshow').cycle('destroy');
		$("#maincontainer").show();
			$("#worklogobox").hide();
	});
	
	$("#stopplay").live('click', function(){
		var wlslideshow = $('#worklogoslideshow').cycle('toggle');
		if (wlslideshow.is(':paused')) {
			$("#stopplay a").removeClass("stop").addClass("play");
			$("#stopplay a").attr('title','Start slideshow');		
		} else {
			$("#stopplay a").removeClass("play").addClass("stop");
			$("#stopplay a").attr('title','Stop slideshow');
		}
		
				
	});			
}

function initPipefitterSlidesPopup() {
	
	if ($('#worklogoslideshow').length > 0) {
		$('#worklogoslideshow').cycle('destroy');
	}

		
	
	$("#pipefitterSlides").each(function(i,e){
		addClickHandler4SlidesTo("#pipefitterSlides", i,e);
	});
	
	$("#topbarclosebutton").live('click', function(){
		$('#worklogoslideshow').cycle('destroy');
		$("#maincontainer").show();
		$("#worklogobox").hide();
	});
	
	$("#stopplay").live('click', function(){
		console.log("stopplay");
		$('#worklogoslideshow').cycle('pause');
		if ($('#worklogoslideshow').is(':paused')) {
			$("#stopplay a").removeClass("stop").addClass("play");
			$("#stopplay a").attr('title','Start slideshow');
			$("#stopplay").attr('id','resumeplay');
		}
	});
	
	$("#resumeplay").live('click', function(){
		console.log("resumeplay");
		$('#worklogoslideshow').cycle('resume');
		$("#resumeplay a").removeClass("play").addClass("stop");
		$("#resumeplay a").attr('title','Stop slideshow');
		$("#resumeplay").attr('id','stopplay');
	});			

}


function memberHover() {
	$("div.lidmaatschappen div.item div.tooltip").each(function(i,e){
		$(e).hide();
		$(e).css('margin-top', -( $(e).height()+5 ) );
	})
	
	$(".lidmaatschappen .item").each(function(i,e){				
		$(e).bind("mouseover",function(){ $("div.tooltip",e).show(); })
		$(e).bind("mouseout",function(){ $("div.tooltip",e).hide(); })
	});
}

function initLijstItems(){
	$("div.lijstitems div.lijstitem").each(function(i,e){
		$(e).attr('id','item'+i);
		$(e).click(function(){
			showWerkzaamheid(i);
		});
	});
}
function showWerkzaamheid(index){
	$(".werkzaamheden_right").each(function(i,e){
		if( i==index ){
			$(e).show();
			$('#item'+i).addClass('selected');
		} else {
			$(e).hide();
			$('#item'+i).removeClass('selected');
		}
	});
}

function showSite(){
	//showVideo();
	initVestigingsLijst();
	showInfoSection(0);
	//addZebraStriping()
}
function showInfoSection( index ){
	$("div.showrooms_item").each(function(i,e){
		if( i===index ){
			$(e).show();
			$("#vestigingitem"+i).addClass("selected");
		} else {
			$(e).hide();
			$("#vestigingitem"+i).removeClass("selected");
		}
	});
}
function initVestigingsLijst(){
	$("div.lijst_vestigingen div.lijstitem").each( function(i,e){
		$(e).attr("id","vestigingitem"+i);
		$(e).click(function(){
			showInfoSection(i);
		});
	} );
}

function addZebraStriping() {
	$("div.dagenholder div.zebra").each( function(i,e) {
		if (i % 2 ) {
			$(e).addClass("dag_wit");
		} else {
			$(e).addClass("dag_grijs");
		}						
	});
}

	
function submitForm(id){
	if( checkForm(id) ){
		//$( '#'+id ).submit();
		return true;
	} else {
		alert( 'U heeft niet alle velden ingevuld!' );	
		return false;
	}
}
function validateEmail( email ){  
	var RE_EMAIL = /^[a-zA-Z.0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+.[a-z]{2,4}$/;
	return RE_EMAIL.test( email );
}
function validateZip(zip) {
    var RE_ZIP = /^[0-9]{4}\s*[a-zA-Z]{2}$/;
    return RE_ZIP.test( zip );
}
function checkForm(id){
	// 	return true;
	var check = true;		

	
	var form =$( '#'+id );
	var labels = $( 'label', form );
	for( i=0; i<labels.length; i++ ){
		if( labels[i].innerHTML.indexOf( '*' ) > -1 ){
			var id = (labels[i]).getAttribute( 'for' );
			var input = $( '#'+id );
			if( input.val() == '' ){
				$(labels[i]).addClass( 'error' );
				input.addClass( 'error' );
				check = false;
			} else {
				$(labels[i]).removeClass( 'error' );
				input.removeClass( 'error' );
			}               
		}
	}

	return check;
}

function initOfferUpload() {
		var settings = {
			// Backend Settings
			flash_url : webappPath + "/js/swfupload22/swfupload.swf",	// Relative to this file
			upload_url: webappPath + "/uploadfiles/mailupload",	// Relative to the SWF file
			post_params: {
			"CAKESESSION" : $("#CmsPageKey").val()	
			, "filePkId" : $("#CmsPageKey").val()
			, "fileType" : "27"										
			},
			// File Upload Settings
			file_size_limit : "10240",	// 10MB maximaal
			file_types : "*.jpg; *.gif; *.png; *.pdf; *.doc; *.docx; *.xls; *.xlsx",
			file_types_description : "Foto, PDF, Word of Excel bestanden",
			file_upload_limit : "0",
			
			// Button Settings
			//button_image_url : webappPath + "/img/offer/offerte-aanvraag-upload.png",
			//button_text: '<span class="offerFont">Voegbestand toe +</span>',
			//button_text_style: ".offerFont { font-family: Arial, Helvetica, sans-serif; font-size: 13px; font-weight: bold; line-height: 14px; color: #ffffff; padding: 0; margin: 0;}",
			button_placeholder_id : "spanButtonPlaceholder",
			button_width: 155,
			button_height: 28,
			button_text : '<span class="button">Voeg bestand toe +</span>',
			button_text_style : '.button { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; }',
			button_text_top_padding: 0,
			button_text_left_padding: 18,			
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_cursor: SWFUpload.CURSOR.HAND,				
			
			// Event Handler Settings - these functions as defined in Handlers.js
			// The handlers are not part of SWFUpload but are part of my website and control how
			// my website reacts to the SWFUpload events.
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			// SWFObject settings
			minimum_flash_version : "9.0.28",
			swfupload_pre_load_handler : swfUploadPreLoad,
			swfupload_load_failed_handler : swfUploadLoadFailed,

			custom_settings : {
				upload_target : "divFileProgressContainer"
			},
			
			// Debug Settings
			debug: false											
			
		};
		
		
		swfu = new SWFUpload(settings);
			
}


function addSlideClickHandlerToWorkLogos(i,e) {	
	addClickHandler4SlidesTo('img.worklogo_large',i, e );
	
	$("img.worklogo_small", e).bind("mouseover",function(){ 
		$("img.worklogo_small",e).hide();
		$("img.worklogo_large",e).show(); 
	
	});
	$("img.worklogo_large", e).bind("mouseout",function(){ 
		$("img.worklogo_large",e).hide();
		$("img.worklogo_small",e).show(); 
	});

	$("#menu").bind("mouseout",function(){
		$("img.worklogo_large").hide();
		$("img.worklogo_small").show();
	});	
}

function addClickHandler4SlidesTo(selector, i, e) {
	var ajax_load = "<div class='ajax_load'><img src='/img/loading/loading.gif' alt='Aan het laden...' /></div>";
	$(selector, e).live('click', function(){
		//alert($(this).attr("rel"));
		$("#maincontainer").hide();
		$("#worklogobox").hide();
		$("#worklogobox").show();
		//first destroy any existing slideshow
     if ($('#worklogoslideshow').length) {
        $('#worklogoslideshow').cycle('destroy');
     }

     var basePath;
		basePath = '/';
		
		if (webappPath == '/cake') {
			basePath = webappPath + '/';	
		} 		
		//then load new data via ajax
		$("#worklogobox").html(ajax_load);
		var ajaxUrl = basePath + 'cms_pages/slideshow/' + $(this).attr("rel"); 
		$.get(  
          ajaxUrl,
         {},  
         function(responseText){  
             $("#worklogobox").html(responseText);
             $('#worklogoslideshow')                 		
				.cycle({ 
				    fx:     'turnLeft',
				    continuous:    0, 
				    speed:  1000,
				    timeout: 4000, 
				    timeoutFn: function (currElement, nextElement, opts, isForward) { 
								return parseInt($(currElement).attr("rel"));
					} , 
				    pager:  '#numbernav',
				    width: '980px',
				    height: '442px',
				    fit: 1 
			});
			var linkStyle = $("#stopplay a").attr('style');
			$("#numbernav a").each(function(i,e){					
				$(e).attr('style', linkStyle);
			});
         },  
         "html"  
     	);  
		
		
		return false;
	});	
}


/*********************
//* jQuery Multi Level CSS Menu (horizontal)- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//* Menu instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//* Last modified: Sept 6th, 08'. Usage Terms: http://www.dynamicdrive.com/style/csslibrary/tos/
*********************/

var jquerycssmenu={

fadesettings: {overduration: 350, outduration: 100}, //duration of fade in/ out animation, in milliseconds

buildmenu:function(menuid){
	//jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
			
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					var menuleft=this.istopheader? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
					$targetul.css({left:menuleft+"px"}).fadeIn(jquerycssmenu.fadesettings.overduration)
				},
				function(e){
					$(this).children("ul:eq(0)").fadeOut(jquerycssmenu.fadesettings.outduration)
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	//}) //end document.ready
}
}

