/**
 * - onload function loader
 * - clear input elements and save default value
 */

//Event.observe(window, 'load', doOnload);
var aOnloadFunctions = new Array();

/**
 * Onload function Load all functions stored in onloadFunctions
 * 
 * @return void
 */
function doOnload()
{
	for(var iIndex = 0; iIndex < aOnloadFunctions.length; iIndex++ )
	{
		if(aOnloadFunctions[iIndex])
		{
			aOnloadFunctions[iIndex]();
		}
	}
}

/**
 * Store a function to run in window.Onload
 * 
 * @param string sName
 * @return void
 */
function addOnloadFunction(sName)
{
	iIndex = aOnloadFunctions.length + 1;

	aOnloadFunctions[iIndex] = sName;
}

function submitMailform( $sID )
{
	jQuery('#'+$sID).submit();
}


function jQuery_deleteRelatedProjectsContent()
{
	$oElement = jQuery('#deleteRelatedProject');
	
	if($oElement)
	{
		$oElement.parent().css('display','none');
	}
}
addOnloadFunction(jQuery_deleteRelatedProjectsContent);


/**
 * Clear default texts: JQuery version of the above
 * 
 * @author Bhe, Kha
 * @version 0.1
 * @copyright Copyright (c) 2011, Zig Websoftware
 * @buildOn jQuery
 */

function jQuery_initClearElementDefaults() 
{
    var aFormInputs = jQuery('input');
    var iInputFields = aFormInputs.length;

    for (var iCounter = 0; iCounter < iInputFields; iCounter++) 
    {
        var oElement = aFormInputs[iCounter];

        if ((oElement.type == 'text' || oElement.type == 'password') && oElement.className.match(/\bcleardefault\b/)) 
        {       
            jQuery(oElement).focus(clearDefaultText);
            jQuery(oElement).blur(replaceDefaultText);
            
            if (oElement.value != '') 
            {
            	oElement.defaultText = oElement.value;
            }
        }
    }
}

function clearDefaultText(e) 
{
    var oTarget = window.event ? window.event.srcElement : e ? e.target : null;
    
    if (!oTarget)
    {
    	return;
    }
    
    if (oTarget.value == oTarget.defaultText) 
    {
    	oTarget.value = '';
    }
}

function replaceDefaultText(e) 
{
    var oTarget = window.event ? window.event.srcElement : e ? e.target : null;
    
    if (!oTarget)
    {
    	return;
    }
    
    if (oTarget.value == '' && oTarget.defaultText) 
    {
    	oTarget.value = oTarget.defaultText;
    }
}

addOnloadFunction(jQuery_initClearElementDefaults);

/**
 * Change styling onfocus and onblur (Kha: translated to jQuery)
 */
function changeColor(oElement, sEventType)
{
	if (sEventType != 'blur')
	{
		jQuery(oElement).css({'border' : '1px solid #E67C0E', 'color' : '#E67C0E'});
	}
	else
	{
		jQuery(oElement).css({'border' : '1px solid #d7d7d7', 'color' : '#d7d7d7'});
	}
}


/*********** menuResize *********/


function menuResize()
{

	jQuery('div#main-menu div.level-2-container-line').each(function(iCounter, oContainer)
	{
		iMaxHeight = jQuery(oContainer).height() - 10;	// the columns have 5px padding above and below, so compensate for that
		jQuery(oContainer).find('.level-2-container-column').height(iMaxHeight);		
	});

	
	jQuery('div#main-menu div.level-2-container').each(function(iCounter, oContainer)
	{
		var iContainerHeight = jQuery(oContainer).height();
		
		var aLines = jQuery(oContainer).find('div.level-2-container-line');
		if (aLines.length == 2)
		{
			var aColumns = jQuery(aLines[1]).find('.level-2-container-column');
			
			// remove line if no secondary columns are present (Mantis 0030175)
			if (aColumns.length == 0)
			{
				jQuery(aLines[1]).remove();
			}
			else
			{
				var iOffsetTop = 11;
				
				// resize the columns
				aColumns.height(iContainerHeight - iOffsetTop - jQuery(aLines[0]).height() - jQuery(oContainer).find('hr').height());
			}
			
		}
	});
	

}

/********** searchForm for dwellings ***********/

// SearchForm class
var SearchForm =
{
	oHideEmptyStorage: new Object(),
	initialize: function()
	{
		jQuery('.search-form').each(function(iCounter, oSearchForm)
		{
			var oSearchForm = jQuery(oSearchForm);
			
			SearchForm.handleHideEmpty();

			oSearchForm.find('select').bind('change', SearchForm.handleChange);
			
			var oSelectContainer = oSearchForm.find('.rent-buy-select').get(0);

			if (oSelectContainer)
			{
				jQuery(oSelectContainer).find('input[type=radio]').bind('click', function(oEvent){
					SearchForm.handleBuyRent(oEvent);
					SearchForm.handleChange(oEvent);

				});
		
				var oFirstElement = jQuery(oSelectContainer).find('input[type=radio]').get(0);
				if (oFirstElement)
				{
					jQuery(oFirstElement).click();
				}
			}
			
			

		});
	},
	handleChange: function(oEvent)
	{
		var oSearchForm = jQuery(oEvent.target).closest('.search-form');
		
		var oForm = jQuery(oSearchForm.find('form').get(0)).serialize();
		
		var aVary = new Array();
		
		oSearchForm.find('.vary').each(function(iCounter, oElement)
		{
			// push the value inside the brackets, e.g. tx_zigwoningaanbod_zig_wa_search[city]: "city" will be pushed
			var sName = oElement.name;
			var aFieldName = sName.match(/\[(.*?)\]/);
			aVary.push(aFieldName ? aFieldName[1] : sName);
		});

		if (aVary.length)
		{
			var sFormRelation = oSearchForm.attr('rel');
			jQuery.getJSON('?type=99&action=vary&searchForm=' + sFormRelation + '&vary=' + aVary.join('|'), oForm, function(aData){
				oSearchForm.find('.vary').each(function(iCounter, oElement)
				{
					var sIndex = null;
					var sName = oElement.name;
					
					
					if (!aData[sName])
					{
						var aFieldName = sName.match(/\[(.*?)\]/);
						sName = aFieldName.length ? aFieldName[1] : null;
						if (!aData[sName])
						{
							sName = null;
						}
					}
					
					if (sName)
					{
						oElement = jQuery(oElement);
						
						if (!oElement.attr('disabled'))
						{
						
							if (oElement.hasClass('hide-empty'))
							{
								
								var sElementValue = oElement.val();
								
								oElement.find('option').remove();
								
								for (var sValue in SearchForm.oHideEmptyStorage[sName])
								{
									if (typeof aData[sName][sValue] != 'undefined' && aData[sName][sValue] != 0)
									{
										var sHtml = SearchForm.oHideEmptyStorage[sName][sValue] + ' [' + aData[sName][sValue] + ']';
										var sSelected = sValue == sElementValue ? ' selected' : '';
										oElement.append('<option value="' + sValue + '" ' + sSelected + '>' + sHtml + '</option>');
									}
								}
							}
							else
							{
							
								for (var sValue in aData[sName])
								{
									var oOption = oElement.find('option[value='+sValue+']');
									var sHtml = jQuery(oOption).html();
									
									if (sHtml && sHtml.indexOf('[') != -1)
									{
										sHtml = sHtml.replace(/\[.*?\]/, '[' + aData[sName][sValue] + ']');
									}
									else
									{
										sHtml += ' [' + aData[sName][sValue] + ']';
									}
																	
									jQuery(oOption).html(sHtml);
									
								}
							}
							
							if (typeof oElement.get(0).refresh == 'function')
							{
								oElement.get(0).refresh();
							}
						}
						
					}
					
					
					
				});
			});
		}
	},
	handleBuyRent: function(oEvent)
	{
		var oSearchForm = jQuery(oEvent.target).closest('.search-form');
		var sCurrent = oSearchForm.find('.rent-buy-select input:checked').val();
		
		oSearchForm.find('.rent-buy-prices-' + sCurrent).show().find('input, select, textarea').removeAttr('disabled');
		oSearchForm.find('.rent-buy-prices-' + (3 - sCurrent)).hide().find('input, select, textarea').attr('disabled','true');
		
		
		// if we selected rent, we do not need variations on the fields. remove the class 'vary'
		if (sCurrent == '1')
		{
			oSearchForm.find('.vary').removeClass('vary').addClass('no-vary');
		}
		else
		{
			oSearchForm.find('.no-vary').removeClass('no-vary').addClass('vary');
		}
	},
	handleHideEmpty: function()
	{
		jQuery('select.hide-empty').each(function(iCount, oElement)
		{
			var sName = oElement.name;
			
			if (sName)
			{
				var aFieldName = sName.match(/\[(.*?)\]/);
				sName = aFieldName.length ? aFieldName[1] : null;
				
				if (sName)
				{
					oElement = jQuery(oElement);
					
					if (typeof SearchForm.oHideEmptyStorage[sName] == 'undefined')
					{
						var oHideEmptyStorage = new Object();
						
						oElement.find('option').each(function(iCounter, oOption)
						{
							oOption = jQuery(oOption);
							oHideEmptyStorage[oOption.val()] = oOption.html().replace(/\s\[.*?\]/, '');
							if (oOption.html().indexOf(' [0]') != -1)
							{
								oOption.remove();
							}
						});
						
						SearchForm.oHideEmptyStorage[sName] = oHideEmptyStorage;
					}
				}
			}
		});
		
	}
};

function openFlipbookPopup(sFile,iHeight,iWidth)
{
	//var sObject = '<object' + 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + iWidth +'px" height="' + iHeight +'px" id="FlipBookBuilder"><param name="movie" value="book.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><!--[if !IE]>--><object type="application/x-shockwave-flash" data="' + sFile +'" width="' + iWidth +'px" height="' + iHeight +'px"><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><!--<![endif]--><!--[if !IE]>--></object> <!--<![endif]--></object>';
	var sObject = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  WIDTH="' + iWidth +'" HEIGHT="' + iHeight +'" id="" ALIGN=""><PARAM NAME=movie VALUE="' + sFile +'"> <PARAM NAME=quality VALUE=high> <EMBED src="' + sFile +'" quality=high WIDTH="' + iWidth +'" HEIGHT="' + iHeight +'" NAME="" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED> </OBJECT>';

	var oPopup = Popup.open({sContent:sObject});
}

function runCarousel()
{
	var sHtml = '';
	
	jQuery('span.news-single-img a').each(function(iCounter, oImgLink)
	{
		if (iCounter != 0)
		{
			var oImg = jQuery(oImgLink).find('img').get(0);
			sHtml += '<li><span><a href="' + oImgLink.href + '" class="rzcolorbox" rel="rzcolorbox"><img src="' + oImg.src + '" width="100" height="75" class="captify" alt="" /></a></span></li>';
			jQuery(oImgLink).remove();
		}
	});
	
	jQuery('span.news-single-img').css('display','block');
	
	if (sHtml)
	{
	
		jQuery('#imagecarousel ul').html(sHtml);
	
	
		jQuery('#imagecarousel').jcarousel({
			auto: 5,
			easing: 'swing',
			animation: 500,
			scroll: 3,
			initCallback: function(carousel,state){imagecarousel.initCallback('#imagecarousel',carousel,state);}
		});
	
		jQuery(".rzcolorbox").colorbox({current:"Afbeelding {current} van {total}",opacity:"0.85",transition:"fade",speed:350,slideshowSpeed:2500,previous:"vorige",next:"volgende",close:"sluit"});
	
		jQuery('#imagecarousel-outer').css('display', 'block');
	}

}


