

function doNothing(){}

///
/// Scripts for Butchery
/// Joris / Nagarajan
///

function performAsynchronousCall(url,redirectURL,errorMessage,textBox){
	var place = encodeURIComponent(document.getElementById(textBox).value);
	redirectURL = redirectURL.replace("##","'");
	//var place = textBox;
	place = $.trim(place);	
	if( place==null  || place==""){
		errorMessage = errorMessage.replace("##","'");
		alert(errorMessage);
		if(document.getElementById(textBox) != null)
		{
			document.getElementById(textBox).focus();
		}
		
	} else {
		var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.prepare&redirectURL='+redirectURL+'&place='+encodeURIComponent(place);
		showCollectionPointPopup(url,ctrlMethod,redirectURL,place);
	}
}

function populateCollectionDates(url,id,textBoxId){

	var selectedValue = document.getElementById(id).value;
	
	var searchText = document.getElementById(textBoxId).value;
	
	var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.prepareCollectionDates&ts='+new Date().getTime()+'&selectedValue='+selectedValue;
	showCollectionPointPopup(url,ctrlMethod,'',searchText);
	
}

function updateOnSelectForGementeList(url,redirectURL,errorMessage){

	var selec = document.getElementsByName('radiobutton');
	
	redirectURL = redirectURL.replace("##","'");

	var selectedValue="a";	
	
	for( x=0;x<selec.length;x++ ) {
	
		if(selec[x].checked){
		
			selectedValue = ""+selec[x].value;
		}
		
	}
	if(selectedValue=='a'){
		errorMessage = errorMessage.replace("##","'");
		alert(errorMessage);
		return;
	}
	
	var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.getCollectionPoints'+'&selectedValue='+selectedValue+'&redirectURL='+redirectURL;
	showCollectionPointPopup(url,ctrlMethod,redirectURL);
	
}

function updateOnSelectForCollectionPoint(url,redirectURL,errorMessage,dateNotSelected,timeNotSelected){	
	
	var selec = document.getElementsByName('radiobutton');
	
	redirectURL = redirectURL.replace("##","'");
	
	var dateValue = document.getElementById('selectDate').value;

	var timeValue = document.getElementById('selectTime').value;
	
	var selectedValue="a";
	
	for( x=0;x<selec.length;x++ ) {
		if(selec[x].checked){
		
			selectedValue = ""+selec[x].value;	
			
		}
		
	}
	if(selectedValue=='a'){
		
		errorMessage = errorMessage.replace("##","'");
		alert(errorMessage);
		return;
	}
	
	if(dateValue == ''){
		
		dateNotSelected = dateNotSelected.replace("##","'");
		alert(dateNotSelected);
		return;
	}
	
	if(timeValue == ''){
		
		timeNotSelected = timeNotSelected.replace("##","'");
		alert(timeNotSelected);
		return;
	}
	
	var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.addCollectionPoint&redirectURL='+redirectURL+'&selectedValue='+selectedValue+'&dateValue='+dateValue+'&timeValue='+timeValue;
	showCollectionPointPopup(url,ctrlMethod,redirectURL);
	
	
}

function updateOnSelectForCollectionDateTime(url,redirectURL,dateNotSelected,timeNotSelected){
	var dateValue = document.getElementById('selectDate').value;
	var timeValue = document.getElementById('selectTime').value;
	
	redirectURL = redirectURL.replace("##","'");
	
	if(dateValue == ''){
		dateNotSelected = dateNotSelected.replace("##","'");
		alert(dateNotSelected);
		return;
	}
	
	if(timeValue == ''){
		timeNotSelected = timeNotSelected.replace("##","'");
		alert(timeNotSelected);
		return;
	}
	var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.addCollectionDateTime&redirectURL='+redirectURL+'&dateValue='+dateValue+'&timeValue='+timeValue;
	showCollectionPointPopup(url,ctrlMethod,redirectURL);
	
	
}
var constants = {
	popupDiv:	".popUpWindow",
	overlayDiv:	"#backgroundOverlay"
};

function showCommentsPopup(url,articleNumber,action,pageId){
        //console.log( arguments );
	return showPopup({
//		url:'/butchery/'
//			+'_DUMMY_POPUP_.jsp'
		url:url+'/AppServlet?m=ArticleCommentsCtrl.prepare&ts='+new Date().getTime()+'&articleNumber='+articleNumber+'&commentAction='+action+'&pageRefreshId='+pageId

			
			//+'incArticleCommentPopup.jsp' //'AppServlet'
			//+'?m=ArticleCommentsCtrl.prepare&ts='+new Date().getTime()
			//+'&articleNumber='+articleNumber
			//+'&commentAction='+action
			//+'&pageRefreshId='+page
	});
};

function showCollectionPointPopup(url,ctrlMethod,redirectURL,place){
//alert(place);
	
	return showPopup({
		//url:'/butchery/'
		//	+'collectionPointPopup.jsp'
		//	+ '?place='+encodeURIComponent(place)
		//	+'&redirectURL='+window.location
		url: url+ctrlMethod
	},'poco',place);
};

function setGeneralComment(){
var textGeneralComment = document.getElementById('reservationComment').value;
textGeneralComment = textGeneralComment.replace(/\n/g, ' ');
textGeneralComment = textGeneralComment.replace(/^\s*|\s*$/g,'');
document.getElementById('hiddenComment').value=textGeneralComment;
}


function displayCollectionPoint(url){

var focusId = 'branchText'; 

	return showPopup({
//		url:'/butchery/'
//			+'collectionPointPopup.jsp'
//			+ '?place='+encodeURIComponent(place)
//			+'&redirectURL='+window.location
		url: url+'/AppServlet?m=CollectionPointCtrl.requestShowPage&fromPopup=Y'
		
	},focusId);
};

function displayModifyHistoryArticles(url){

//var focusId = 'branchText'; 

	return showPopup({
//		url:'/butchery/'
//			+'collectionPointPopup.jsp'
//			+ '?place='+encodeURIComponent(place)
//			+'&redirectURL='+window.location
		url: url+'/AppServlet?m=ShoppingCartCtrl.showModifyHistoryArticles&fromPopup=Y'
		
	});
};

function displayHistoryModifyConfirmPopUp(url){

//var focusId = 'branchText'; 

	return showPopup({
//		url:'/butchery/'
//			+'collectionPointPopup.jsp'
//			+ '?place='+encodeURIComponent(place)
//			+'&redirectURL='+window.location
		url: url+'/AppServlet?m=ShoppingCartCtrl.showModifyHistoryConfirmPopUp&fromPopup=Y'
		
	});
};


function displayCollectionDateAndTime(url,branchNumber){

var focusId = 'branchText'; 

	return showPopup({
		url: url+'/AppServlet?m=CollectionPointCtrl.requestShowDateTimePage&fromPopup=Y&branchNumber='+branchNumber
		
	},focusId);
};

function showArticleDetailImagePopup(url,imgPath,title){
	return showPopup({
//		url:'/butchery/'
//			+'_DUMMY_POPUP_.jsp'
		url: url+'/AppServlet?m=ArticleDetailCtrl.requestEnlargeImage', 
                callback : { apply : function(elm,opts){
                        var popup = $(opts.selector);
                        if(typeof title != undefined){
                            popup.find('.heading span').text(title);
                        } else {
                            var title = "";
                        }
                        if(typeof imgPath != undefined){
                            popup.find('.image .graphic img').attr({src:imgPath, alt: title});
                        }
                }}

			//+'AppServlet' +
			//+'?m=ArticleCommentsCtrl.prepare&ts='+new Date().getTime()
			//+'&articleNumber='+articleNumber
			////+'&commentAction='+action
			//+'&pageRefreshId='+pageId*/
	});
};

function showBranchMapImagePopup(url,imgPath,title){
	return showPopup({
//		url:'/butchery/'
//			+'_DUMMY_POPUP_.jsp'
		url: url+'/AppServlet?m=ColruytSiteCtrl.requestEnlargeMap', 
                callback : { apply : function(elm,opts){
                        var popup = $(opts.selector);
                        if(typeof title != undefined){
                            popup.find('.heading span').text(title);
                        } else {
                            var title = "";
                        }
                        if(typeof imgPath != undefined){
                            popup.find('.image .graphic img').attr({src:imgPath, alt: title});
                        }
                }}

			//+'AppServlet' +
			//+'?m=ArticleCommentsCtrl.prepare&ts='+new Date().getTime()
			//+'&articleNumber='+articleNumber
			////+'&commentAction='+action
			//+'&pageRefreshId='+pageId*/
	});
};

// ****************************************************************************************************************/
function showPopup(opts,focusId,place){

	opts=val(opts);
	$.ajax({
		url: opts.url,
	   	cache: (opts.cache===true?true:false),
	   	error: function(xhrobj,textStatus, errorthrown){
	   		//alert errors are dirty.
	   	   	//alert(opts.error||('Ajax failed: '+errorthrown));
		},   
		success: function(data) {
			$(opts.selector).ready(function(){
			    $(opts.selector).html(data);
				// recalculate position, because only now (after inserted into document)
				// we know the exact size of the popup
				opts.top=opts.left=false;
				opts=val.position(opts);
				$(opts.selector).css({
					"display":	opts.display,
					"position":	opts.position,
					"top": 		opts.top,
					"left": 	opts.left
				});
                                var h_win = ($.browser.msie) ? document.documentElement.offsetHeight : window.innerHeight;
                                var h_cnt = $("#pageContainer").height();
                                $(opts.overlay).height(Math.max(h_win,h_cnt));
				$(opts.overlay).css({"display":opts.display});
				extractScriptHTML(data);
				if(opts.callback)opts.callback.apply(this,opts);
			});
			
			//alert('form to submit '+document.getElementById('formToSubmit'));
			//alert('poco id -->'+document.getElementById('poco'));
			//alert('place '+place);
			if(document.getElementById('poco') !=null){
			
				document.getElementById('poco').focus();
							
			}
			if(document.getElementById('formToSubmit') ==null){
					//cljs.Overlayer.displayBlock('#overlayPostal');
						
						//$("#poco").ready().val(place);
						if(document.getElementById('poco') !=null){
							$("#poco").ready(function(){
					
								setTimeout(function(){document.getElementById('poco').focus();},10);
								
							}).val(place);
						}
			}
		}
	});
	/*$("#"+focusId).ready(function(){
	alert('inside set focus '+focusId);
				
					setTimeout(function(){document.getElementById(focusId).focus();},10);
				
				});*/
	return false;
};

// ****************************************************************************************************************/

// ****************************************************************************************************************/

function hidePopup(opts){
	opts=val(opts);
	$(opts.selector).css({"display":"none"});
	//$(opts.overlay).remove();
	$(opts.overlay).css({"display":"none"});
};

function val(opts){
	opts=opts||{};
	opts.selector=opts.selector||constants.popupDiv;
	opts.overlay=opts.overlay||constants.overlayDiv;
	opts.position=opts.position||"absolute";
	opts.display=opts.display||"block";
	
	return val.position(opts);	
};

val.position = function(opts){
	opts.top=(opts.top||(( $(window).height() - $(opts.selector).height() ) / 2  + "px"));
	opts.left=(opts.left||(($(window).width() - $(opts.selector).width()) / 2  + "px"));
	return opts;
};

// Finally, try to hide the popup on page load
try{$(document).ready(function(){hidePopup();});}catch(e){/* hide failed */}



function articleCommentAction(url,articleNumber,fromPage,pageRefreshId,action, errorCommentLengthExceeded, errorCommentEmpty){

var ctrl = new String();
	if(action == 'add'){
		ctrl = 'ArticleCommentsCtrl.requestAdd&fromAjax=Y';
	}else if(action == 'modify'){
		ctrl = 'ArticleCommentsCtrl.requestModify&fromAjax=Y';
	}else if(action == 'delete'){
		ctrl = 'ArticleCommentsCtrl.requestDelete&fromAjax=Y';
	}

	var textComment = document.getElementById('textComment').value;
	textComment = textComment.replace(/\n/g, ' ');
	textComment = textComment.replace(/^\s*|\s*$/g,'');
	if(textComment.length == 0){
		errorCommentEmpty = errorCommentEmpty.replace("##","'");
		alert(errorCommentEmpty);
		var textCommentArea  = document.getElementById('textComment');
		if(textCommentArea!=null){
		setTimeout(function(){document.getElementById('textComment').focus();},10);
		textCommentArea.focus();
				}
		return;
	}else if(textComment.length>2000){
		errorCommentLengthExceeded = errorCommentLengthExceeded.replace("##","'");
		alert(errorCommentLengthExceeded);
		var textCommentArea  = document.getElementById('textComment');
		if(textCommentArea!=null){
		setTimeout(function(){document.getElementById('textComment').focus();},10);
		textCommentArea.focus();
				}
		return;
	}
	
	$.ajax(
		{
			//url: url+'/AppServlet?m=ArticleCommentsCtrl.requestAdd&ts='+new Date().getTime()+'&articleNumber='+articleNumber+'&fromPage='+fromPage+'&comment='+textComment,  
			url: url+'/AppServlet?m='+ctrl+'&ts='+new Date().getTime()+'&articleNumber='+articleNumber+'&fromPage='+fromPage+'&comment='+encodeURIComponent(textComment),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    
		    	$('#'+pageRefreshId).html(data);
			}
		}
	);
	
	return false;
}

//Included for butchery START
function prepareShoppingCart(url,id,page){

	var ctrl = new String();
	if(page == 'basket'){
		ctrl = 'ShoppingCartCtrl.prepareForShoppingCartPage&fromAjax=Y';
	}else if(page == 'checkout'){
		ctrl = 'ShoppingCartCtrl.prepareForCheckout&fromAjax=Y';
	}else if(page == 'rightnavigation'){
		ctrl = 'ShoppingCartCtrl.prepareForRightNavigation&fromAjax=Y';
	}
		
	$.ajax(
		{
			url: url+'/AppServlet?m='+ctrl+'&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
			$("#"+id).ready(function(){
					$('#'+id).html(data);
					cljs.SpinnerManager.initPage();
			});
			
			//extractScriptHTML( data);
			    
			    //executeNoSessionScript();
			}
		}
	);
}

function prepareHistoryList(url,id){

	var ctrl = new String();
	
	ctrl = 'ButcheryHistoryListCtrl.prepareHistoryByCbhID';
			
	$.ajax(
		{
			url: url+'/AppServlet?m='+ctrl+'&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
			$("#"+id).ready(function(){
					$('#'+id).html(data);
					cljs.SpinnerManager.initPage();
			});
			
			//extractScriptHTML( data);
			    
			    //executeNoSessionScript();
			}
		}
	);
}

function requestCustomerCreate(url,pageIdToRefresh){
	
	$.ajax(
		{
			url: url+'/AppServlet?m=InschrijvingCtrl.prepareCustomerCreation&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('.'+pageIdToRefresh).html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function customerCreation(url,pageIdToRefresh){
	
	$.ajax(
		{		
			url: url+'/AppServlet?m=InschrijvingCtrl.requestValideerKlantForCreation&ts='+new Date().getTime()+formUserParameters('create'),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('.'+pageIdToRefresh).html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function requestCustomerModify(url){
		
	$.ajax(
		{
			url: url+'/AppServlet?m=InschrijvingCtrl.requestRegistration&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#userLogIn').html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function requestUserAuthentication(url,usernameId,passwordId,pageIdToRefresh){
		
		var logonid = encodeURIComponent(document.getElementById(usernameId).value);
		var password = encodeURIComponent(document.getElementById(passwordId).value);
	$.ajax(
		{
		
			url: url+'/AppServlet?m=LoginCtrl.requestZoekKlant&ts='+new Date().getTime()+'&viewLogonid='+logonid+'&viewPaswoord='+password,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
			
			//var wizardClass = "wizardPage nl";
			//var personalListClass = "personalPage nl";
			$('#'+pageIdToRefresh).html(data);
			
			}
		}
	);
	
	return false;
}

function requestZoekLandCodeCreate(url){
		
	var viewLand = encodeURIComponent(document.getElementById('plaats').value);
		
	$.ajax(
		{
			url: url+'/AppServlet?m=InschrijvingCtrl.zoekLandCodeCustCreate&ts='+new Date().getTime()+'&viewLand='+viewLand,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#userLogIn').html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function requestZoekLandCodeModify(url){
		
	var viewLand = encodeURIComponent(document.getElementById('plaats').value);
		
	$.ajax(
		{
			url: url+'/AppServlet?m=InschrijvingCtrl.zoekLandCodeCustModify&ts='+new Date().getTime()+'&viewLand='+viewLand,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#userLogIn').html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function customerRegistration(url){
		
	$.ajax(
		{
		
			url: url+'/AppServlet?m=InschrijvingCtrl.requestValideerKlant&ts='+new Date().getTime()+formUserParameters('modify'),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#userLogIn').html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function logOut(){
document.logoutFom.submit() ;
}

function requestForgotPassword(url,pageIdToRefresh){

	$.ajax(
		{
			url: url+'/AppServlet?m=PasswordForgottenCtrl.requestForgotPwdPrepare&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#'+pageIdToRefresh).html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}
function forgotPassword(url,pageIdToRefresh){
		var email = encodeURIComponent(document.getElementById('emailId').value);
	$.ajax(
		{
			url: url+'/AppServlet?m=PasswordForgottenCtrl.requestSearchLogons&ts='+new Date().getTime()+'&email='+email,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('.'+pageIdToRefresh).html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function formUserParameters(type){
	var parameter = new String();
		var viewAanspreektitel = encodeURIComponent(document.getElementById('apktitel').value);
		var viewTaal = encodeURIComponent(document.getElementById('taal').value);
		var viewNaam = encodeURIComponent(document.getElementById('naam').value);
		var viewVoornaam = encodeURIComponent(document.getElementById('voornaam').value);
		var viewStraat = encodeURIComponent(document.getElementById('straat').value);
		var viewNummer = encodeURIComponent(document.getElementById('huisnum').value);
		var viewBus = encodeURIComponent(document.getElementById('bus').value);
		var viewGemeente = encodeURIComponent(document.getElementById('gemeente').value);
		var viewPostCode = encodeURIComponent(document.getElementById('postcode').value);
		var viewLand = encodeURIComponent(document.getElementById('plaats').value);
		
		var viewTelPriveLandnr = encodeURIComponent(document.getElementById('telprivelandnr').value);
		var viewTelPrive = encodeURIComponent(document.getElementById('telprive').value);
		
		var viewTelWerkLandnr = encodeURIComponent(document.getElementById('telwerklandnr').value);
		var viewTelWerk = encodeURIComponent(document.getElementById('telwerk').value);
		
		var viewGsmPriveLandnr = encodeURIComponent(document.getElementById('gsmprivelandnr').value);
		var viewGsmPrive = encodeURIComponent(document.getElementById('gsmprive').value);
		
		var viewGsmWerkLandnr = encodeURIComponent(document.getElementById('gsmwerklandnr').value);
		var viewGsmWerk = encodeURIComponent(document.getElementById('gsmwerk').value);
		
		var viewEmail = encodeURIComponent(document.getElementById('email').value);
		var viewUserName = encodeURIComponent(document.getElementById('user').value);
		
		var viewNewPassword = encodeURIComponent(document.getElementById('npswd').value);
		var viewConfirmPassword = encodeURIComponent(document.getElementById('rpswd').value);
		
		if(type.toLowerCase()=="create".toLowerCase()){
			parameter = '&viewAanspreektitel='+viewAanspreektitel+'&viewTaal='+viewTaal+'&viewNaam='+viewNaam+'&viewVoornaam='+viewVoornaam+'&viewStraat='+viewStraat+'&viewNummer='+viewNummer+'&viewBus='+viewBus+'&viewGemeente='+viewGemeente+'&viewPostCode='+viewPostCode+'&viewLand='+viewLand+'&viewTelPriveLandnr='+viewTelPriveLandnr+'&viewTelPrive='+viewTelPrive+'&viewTelWerkLandnr='+viewTelWerkLandnr+'&viewTelWerk='+viewTelWerk+'&viewGsmPriveLandnr='+viewGsmPriveLandnr+'&viewGsmPrive='+viewGsmPrive+'&viewGsmWerkLandnr='+viewGsmWerkLandnr+'&viewGsmWerk='+viewGsmWerk+'&viewEmail='+viewEmail+'&viewUserName='+viewUserName+'&viewNewPassword='+viewNewPassword+'&viewConfirmPassword='+viewConfirmPassword
		}else{
			var viewPassword = encodeURIComponent(document.getElementById('pswd').value);
			parameter = '&viewAanspreektitel='+viewAanspreektitel+'&viewTaal='+viewTaal+'&viewNaam='+viewNaam+'&viewVoornaam='+viewVoornaam+'&viewStraat='+viewStraat+'&viewNummer='+viewNummer+'&viewBus='+viewBus+'&viewGemeente='+viewGemeente+'&viewPostCode='+viewPostCode+'&viewLand='+viewLand+'&viewTelPriveLandnr='+viewTelPriveLandnr+'&viewTelPrive='+viewTelPrive+'&viewTelWerkLandnr='+viewTelWerkLandnr+'&viewTelWerk='+viewTelWerk+'&viewGsmPriveLandnr='+viewGsmPriveLandnr+'&viewGsmPrive='+viewGsmPrive+'&viewGsmWerkLandnr='+viewGsmWerkLandnr+'&viewGsmWerk='+viewGsmWerk+'&viewEmail='+viewEmail+'&viewUserName='+viewUserName+'&viewPassword='+viewPassword+'&viewNewPassword='+viewNewPassword+'&viewConfirmPassword='+viewConfirmPassword
		}
	return parameter;
}

function addAllProdToCartNonModify(url,id,page){
	$.ajax(
		{
			url: url+'/AppServlet?m=ShoppingCartCtrl.reqAllArticlesToCartNonModify&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#'+id).html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}

function addProductToShoppingCart(textId,unitId,url,techNumber,invalidNumber,quantityExceeded,id,page){
		
		var regExp ;
		var quantity = document.getElementById(textId).value;
		var unit = document.getElementById(unitId).value;
		if(unit == "G")
		{
			regExp = ("^[\.|,]?[0-9]+[\.|,]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?$");
		}
		else
		{
			regExp = ("^[0-9]+[0-9]?[0-9]?[0-9]?$");
		}
		if( quantity==null  || quantity=="" || quantity==0){
			invalidNumber = invalidNumber.replace("##","'");
			alert(invalidNumber);
			if(document.getElementById(textId) != null)
			{
				document.getElementById(textId).focus();
			}
			return false;
		}
			else{ 
				if(!quantity.match(regExp)){
					invalidNumber = invalidNumber.replace("##","'");
					alert(invalidNumber);
					if(document.getElementById(textId) != null)
					{
						document.getElementById(textId).focus();
					}
					return false;
				}else if(quantity>=10000){
					quantityExceeded = quantityExceeded.replace("##","'");
					alert(quantityExceeded);
					if(document.getElementById(textId) != null)
					{
						document.getElementById(textId).focus();
					}
					return false;
				}
			else
			{
				$.ajax(
					{
						url: url+'/AppServlet?m=ShoppingCartCtrl.requestAddToShoppingCart&ts='+new Date().getTime()+'&techNumber='+techNumber+'&quantity='+quantity+'&unit='+unit,
				    	cache: false, 
				    	error: function(xhrobj,textStatus, errorthrown){
				    	   	alert('ajax failed'+errorthrown);
						},   
						success: function(data) {
						
						if (jQuery.browser.msie){  
				 			$('#wrap').remove();
       					}
						    $('#shoppingCart').html(data);
						    document.getElementById(textId).value = 1;
						    //Check is it mandatory call
						    //extractScriptHTML( data);
						    if(id != 'shoppingCart'){
						    	prepareShoppingCart(url,id,page);
						    }
						}
					}
				);
			}
			}
		return false;
}

function extractScriptHTML(html){
		/**
		 * delete previous script input to avoid profileration of scripts
		 */
		/*var Node =document.getElementById(target);
		if (Node!=null) {
			Node.parentNode.removeChild(Node);
		}*/
	
		/**
		 * parse new content and put script in <head>
		 */
		var recogStartJs = "<script";
		var recogEndJs = "<\/script>";
		var scriptFound = false;
	
		var head= document.getElementsByTagName('head')[0];
		var script= document.createElement('script');
		script.type= 'text/javascript';
		//script.id=target;
	
		while(html.indexOf(recogStartJs) != -1) {
			
			scriptFound = true;
			var startPos = html.indexOf(recogStartJs);
			var startPosScript = html.indexOf(">", startPos + recogStartJs.length)
			var stopPos = html.indexOf(recogEndJs);
			
			var js = html.substring(startPosScript + 1, stopPos);
	
			html = html.substring(0, startPos) + html.substring(stopPos + recogEndJs.length);
			script.text= script.text + js;
			
		}
		
		if(scriptFound){
			head.appendChild(script);
		}
	
		return html;
}

function removeProductFromShoppingCart(url,techNumber,id,page){
	$.ajax(
		{
			url: url+'/AppServlet?m=ShoppingCartCtrl.requestRemoveFromShoppingCart&ts='+new Date().getTime()+'&techNumber='+techNumber,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
				if (jQuery.browser.msie){  
					$('#wrap').remove();
       			}
			
			    $('#shoppingCart').html(data);
			    
			    prepareShoppingCart(url,id,page);
			    
			    
			}
		}
	);
	return false;
}

function removeProductFromPersonalList(url,techNumber){
		//alert('techNumber  '+techNumber);
	$.ajax(
		{
			url: url+'/AppServlet?m=ButcheryPersonalListCtrl.requestRemoveArticle&ts='+new Date().getTime()+'&techNumber='+techNumber,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
			    $('#personalListPage').html(data);
			    cljs.SpinnerManager.initPage();
			    //executeNoSessionScript();
			    //extractScriptHTML( data);


			}
		}
	);
	return false;
}

function removeProductFromPersonalListPageRefresh(url,techNumber,pageRefreshId){
		//alert('techNumber  '+techNumber);
	$.ajax(
		{
			url: url+'/AppServlet?m=ButcheryPersonalListCtrl.requestRemoveArticleForPageRefresh&ts='+new Date().getTime()+'&techNumber='+techNumber,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
			    $('#'+pageRefreshId).html(data);
			}
		}
	);
	return false;
}

function addProductToPersonalList(url,techNumber,fromPage,fromPageId){
		//alert('techNumber  '+techNumber);
	$.ajax(
		{
			url: url+'/AppServlet?m=ButcheryPersonalListCtrl.requestAddArticle&ts='+new Date().getTime()+'&techNumber='+techNumber+'&fromPage='+fromPage,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
				//$('#'+fromPageId).html(data);
				document.getElementById(fromPageId).innerHTML = data;
				
				$('body').attr('class','personalPage nl');
				
				extractScriptHTML( data);
			
			}
		}
	);
	return false;
}

function addProductListToPersonalList(url,fromPage,fromPageId){
		//alert('techNumber  '+techNumber);
	$.ajax(
		{
			url: url+'/AppServlet?m=ButcheryPersonalListCtrl.requestAddAllArticlesToPersonalList&ts='+new Date().getTime()+'&fromPage='+fromPage,  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			
				$('#'+fromPageId).html(data);
				//document.getElementById(fromPageId).innerHTML = data;
				
				$('body').attr('class','personalPage nl');
				
				//extractScriptHTML( data);
			
			}
		}
	);
	return false;
}
function enlargeButcheryBranchImage(url,imgPath,title){
	return showPopup({
//		url:'/butchery/'
//			+'_DUMMY_POPUP_.jsp'
		url: url+'/AppServlet?m=ColruytSiteCtrl.requestEnlargeImage', 
                callback : { apply : function(elm,opts){
                        var popup = $(opts.selector);
                        if(typeof title != undefined){
                            popup.find('.heading span').text(title);
                        } else {
                            var title = "";
                        }
                        if(typeof imgPath != undefined){
                            popup.find('.image .graphic img').attr({src:imgPath, alt: title});
                        }
                }}

			//+'AppServlet' +
			//+'?m=ArticleCommentsCtrl.prepare&ts='+new Date().getTime()
			//+'&articleNumber='+articleNumber
			////+'&commentAction='+action
			//+'&pageRefreshId='+pageId*/
	});
};
/*function enlargeButcheryBranchImage(url){
		
	$.ajax(
		{
		
			url: url+'/AppServlet?m=ColruytSiteCtrl.requestEnlargeImage&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#shopBigImage').html(data);
			    //executeNoSessionScript();
			}
		}
	);
	
	return false;
}*/

function maxLengthTextArea(aTextArea, aMaxLength) {
//alert(aTextArea.value);
	if (aTextArea.value.length > aMaxLength) {
 		aTextArea.value = aTextArea.value.substr(0, aMaxLength);
    }
	return true;
}

 // options:
                        // wordcut        > true|false > cut off whole words
                        // trim                > true|false > don't count in the spaces at the end

  var cutter = function(o,opts){
                        	if(o.clientWidth){
                                opts = opts || {};
                                this.wordcut = opts.wordcut===false?false:true;
                                this.trim = opts.trim===false?false:true;
                                var h,tmp,i=-1,p=0,rx=/\w/,
                                t = o.textContent||o.innerText,
                                ppp = document.createTextNode("..."); // or \u2026
                                if(Math.max(o.scrollWidth/o.clientWidth, o.scrollHeight/o.clientHeight)>1){
                                        while(o.childNodes.length > 0) o.removeChild(o.firstChild);
                                        o.appendChild(ppp);
                                        h=o.scrollHeight;
                                        do{
                                                tmp="";
                                                do tmp += t.substr(p++,1);
                                                while(
                                                        i++ &&
                                                        (this.trim && tmp.substr(i,1)==" ") ||
                                                        (this.wordcut && p<=t.length && rx.test(t.substr(p,1)))
                                                );
                                                tmp = document.createTextNode(tmp);
                                                o.insertBefore(tmp, ppp);
                                        }while((o.scrollWidth <= o.clientWidth) && (o.scrollHeight <= Math.max(o.clientHeight,h)) && p<t.length && (i=-1));
                                        o.removeChild(p>=t.length?ppp:tmp);
                                       	o.innerHTML = o.innerHTML; //IE HACK
                                       	o.normalize();
                                }
                        	}
                        }


function showFlashVideo(flashObj,url,location,xmlPath,height,width){
	
	var so = new SWFObject(url+"/static/style/site/"+location+"?t="+new Date().getMilliseconds() , "anim", width, height, "8", "#ffffff");
	
	so.addVariable("xmlpath", url+"/static/style/xml/"+xmlPath );		
	
	so.addParam("wmode", "transparent");
	
	so.write(flashObj);
	
}

function performGAForFaultPage(gaTagId,gaDomainName){

	try {
				var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
				
				document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
	
				var pageTracker = _gat._getTracker(gaTagId);
				
				pageTracker._setDomainName(gaDomainName);
				
				pageTracker._setAllowLinker(true);
				
				pageTracker._setAllowHash("false");
				
				pageTracker._link();
				
				pageTracker._linkByPost();
				
				pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);
				
	} catch(err) {}
}

function performGAForAjaxCall(gaTagId,pageName,gaDomainName,gaSrcCodeObject){

	var gaJsHost = (("https:" == document.location.protocol) ? decodeURIComponent("https%3A%2F%2Fssl.") : decodeURIComponent("http%3A%2F%2Fwww."));
				setTimeout(function(){gaSrcCodeObject.src=gaJsHost + "google-analytics.com/ga.js";
				setTimeout(function(){try{var pageTracker = _gat._getTracker(gaTagId);
				pageTracker._setDomainName(gaDomainName);
				pageTracker._setAllowLinker(true);
				pageTracker._setAllowHash("false");
				pageTracker._link();
				pageTracker._linkByPost();
				pageTracker._trackPageview(pageName);}catch(e){}
				},300);},500);
}

function getDomainName(){
			        var sDom = window.location.hostname.split('.');
			        if (sDom && sDom.length > 2) {
			            return ("." + sDom[sDom.length - 2] + "." + sDom[sDom.length - 1]);			            
			        } else {
			            return ("." + window.location.hostname);
			        }
}

function printFunc(){
			window.print();
}

//Included for butchery END

function expandTypeValue(url){
	
	// Add effects if needed,  just adding a time will create it
	$.ajax(
		{
			url: url,
			success: function onSuccess(data){
				$("#facetList").html(data);
				//executeNoSessionScript();
			},
			error: function handleError(data){
			},
			cache: false 
		}
	);
}

function showResultsForPageArticle(url,id){

	//var pageNumber = myPageNumber.name;
	$.ajax(
		{
			url: url,
			success: function onSuccess(data){
				$("#"+id).html(data);
				extractScriptHTML( data);
				//executeNoSessionScript();
			},
			error: function handleError(data){
			},
			cache: false 
		}
	);
}




function performArticleSort(url,sortid,contentid){
	
//	var afterSort = new YAHOO.util.CustomEvent("afterSort");
//	afterSort.subscribe(populatePriceAfterSort);
	
	var sortOrder = document.getElementById(sortid).value;
	
	$.ajax(
		{
			url: url+'&sorting='+sortOrder,
			success: function onSuccess(data){
				$("#"+contentid).html(data);
				extractScriptHTML( data);
				//executeNoSessionScript();
			},
			error: function handleError(data){
			},
			cache: false 
		}
	);
	
}

function submitForm(){
		
	document.dummyForm.submit();
}


// Script :-------------Compare article-------------
function addProductToCompare(url,assetid,isProdPage){
	
		$.ajax(
			{
				url: url+'/AppServlet?m=CompareArticlesCtrl.requestAddToCompare'+'&assetId='+assetid+'&isProdPage='+isProdPage,
				success: function onSuccess(data){
				
					$("#compareArticleBox").html(data);
					//executeNoSessionScript();
					setTimeout("ga();",800);
					
				},
				error: function handleError(data){
				},
				cache: false 
			}
		);
}
function removeProductFromCompare(url,assetid){
		
		$.ajax(
			{
				url: url+'/AppServlet?m=CompareArticlesCtrl.requestRemoveFromCompare'+'&assetId='+assetid,
				success: function onSuccess(data){
				
					$("#compareArticleBox").html(data);
					//executeNoSessionScript();
				},
				error: function handleError(data){
				},
				cache: false 
			}
		);
}

function checkForCompare(size){

	if(size < 2){
			$("#box_compare_error_msg").css("display", "none");
			$("#box_compare_error_min").css("display", "block");
			$("#box_compare_error_hide").css("display", "block");
			return false;
	}else {
			return true;
	}
}
/*function pageWidth() {return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;}
function pageHeight() {return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;}*/

function pageWidth()
{
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

function pageHeight()
{
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
} 

function requestToChangeCompareArticle(url,index,browserUrl){
		
		//Dom.setStyle('changeCompareArticlePopup','display','block');
		browserUrl = encodeURIComponent(browserUrl);
		$.ajax(
			{
				url: url+'&index='+index+'&browserUrl='+browserUrl,
				success: function onSuccess(data){
					
					$("#overlayCompare").html(data);
					extractScriptHTML( data);
					cljs.Overlayer.displayBlock('#overlayCompare');
					//executeNoSessionScript();
					//executeFontSetScript();
				},
				error: function handleError(data){
				},
				cache: false 
			}
		);
}


function asyncCallUpdateDeliveryDate(url, assetId, elementId){
		
		$.ajax(
			{
				url: url+'&assetId='+assetId,
				success: function onSuccess(data){
				
					$("#"+elementId).html(data);
					//executeNoSessionScript();
				},
				error: function handleError(data){
				},
				cache: false 
			}
		);
}

function performUpdateDeliveryDate(url , assetIdArray){
		
		var deliveryDateId = null;
		for(i = 0; i < assetIdArray.length; i++){
				deliveryDateId = 'deliveryDate'+assetIdArray[i];
				asyncCallUpdateDeliveryDate(url, assetIdArray[i], deliveryDateId);
		}
}


function changeStyleDelCompArt(artNameId){

	$("#"+artNameId).css({"color": "#FF0000", "text-decoration": "line-through"});
}
function revertStyleDelCompArt(artNameId){

	$("#"+artNameId).css({"color": "", "text-decoration": "none"});
}

function toggleShowArtDescCompare(i){
alert("also here");
	var link = 'link'+i;
	$("#"+link).click(function(){
		$("div.compareDescFull").toggle();
		$("div.compareDescPart").toggle();
	}
	);	
}
//$("#toggleMore").toggle(
//  function () {  	
//   	for(index=0; index < listSize; index++){	
//   		$("#compareDescFull"+index).css("display", "block");
//   		$("#compareDescPart"+index).css("display", "none");
//	}
//  },
// function () {  	
//    for(index=0; index < listSize; index++){	
//   		$("#compareDescFull"+index).css("display", "none");
//   		$("#compareDescPart"+index).css("display", "block");
//	}
//  }
//);	
//}
// END Script :-------------Compare article-------------

function triggerSubmit(event, id){
	if(window.event){
	 	e=window.event;
	 } 
    if (event.keyCode == 13) {
	 	document.getElementById(id).click();
	 	return false;
	 } else {
	 	return true;
	 }
}
function getModulePopupWidth(width) {
	var xpos = (pageWidth() - width)/ 2;
	
	if(xpos < 0) {
	
		xpos = 0;
		
	}
	
	return xpos;
	
}

function getModulePopupHeigth(height) {

	var ypos = (pageHeight() - height)/2;
	
	if(ypos < 0) {
	
		ypos = 0;
	
	}
	
	return ypos;

}

function createModule(header,footer,source){


	var myPopup = new YAHOO.widget.Panel("magnifiedImage", { 
	modal:true ,
	x:getModulePopupWidth(530),
	y:getModulePopupHeigth(400),
	draggable: true,
	constrainttoviewport: true,
	fixedcenter:false,
	close:true,
	width: "530px",
	underlay: "shadow"
	 });
	myPopup.setHeader(header);
	document.getElementById('bdy').innerHTML = '<img src="'+source+'" alt=""></img>';
	$("#magnifiedHead").css("background","#FFFFFF");
	myPopup.render(document.body);
}

function showFullArtDescr() {
	
	$("#halfDesc").css("display", "none");
	$("#fullDesc").css("display", "block");
	$("#cr-footer").addClass("rePaint");
}
function showDeliveryDate(url){

	$.ajax(
	{
		url: url+'/AppServlet?m=ProductInfoCtrl.requestDeliveryDate&ts='+new Date().getTime(),  
    	cache: false, 
    	success: function onSuccess(data) {
    		if($('#deliveryDateDetail').html != null)
    		{
    			 $('#deliveryDateDetail').html(data);	
    			 //executeNoSessionScript();
    		}
		   
		},
    	error: function onFailure(){
    	   	
		}   

	}
		
	);

}



function addToShoppingCartOnEnter(e,id){
	
	if (e.keyCode == 13) {
    	var callAddToShoppingCart = document.getElementById(id).onclick;
    	 callAddToShoppingCart();
    	return false;
    } else {
		return true;
	}
}
function ga(){			
	eval(document.getElementById('performAnalytics').innerHTML);
}


function shoppingCartDetails(url){
		
	$.ajax(
		{
			url: url+'/AppServlet?m=ShoppingCartCtrl.requestShoppingCartDetails&ts='+new Date().getTime(),  
	    	cache: false, 
	    	error: function(xhrobj,textStatus, errorthrown){
	    	   	alert('ajax failed'+errorthrown);
			},   
			success: function(data) {
			    $('#allContainer').html(data);
			    //executeNoSessionScript();
			}
		}
	);
}

/*
function showCollectionPointPopup(place,applName){

		$.ajax(
		{
			
			url: applName+'/AppServlet?m=CollectionPointCtrl.requestShowPage&fromPopup=Y',
			
			success: function onSuccess(data){
				
				$("#overlayPostal").html( data );
				
				cljs.Overlayer.displayBlock('#overlayPostal');
				
				$("#poco").ready(function(){
				
					setTimeout(function(){document.getElementById('poco').focus();},10);
				
					colPointTextBox.focus();
				});
			},
			error: function handleError(data){
			},
			cache: false 
		}
	);
	
	
}
*/

function showFlash(flashObj,url,location,xmlPath,width,height){

	var so = new SWFObject(url+"/resource/"+location+"?t="+new Date().getMilliseconds(), "anim", width, height, "8", "#ffffff");
	
	so.addVariable("xmlpath", xmlPath );
						
	so.addParam("wmode", "transparent");
						
	so.write(flashObj);
	
}

function showSubMenu(parentId, childListId){
	var timeout = 150;
	var f = function(){
		showSubMenu.item = childListId;
		var overlay1 = new YAHOO.widget.Overlay(
			childListId,
			{
			     context:[parentId,"tl","tr",["beforeShow", "windowResize"]],
			     iframe:false
			}
		);
		$("#"+childListId).css("display","block");		
		overlay1.render();
		$("#"+childListId+"Parent").addClass("navHovered");
	}
	if(showSubMenu.item == childListId){
		f();
	}else{
		showSubMenu.timer = window.setTimeout(f,timeout);
	}
}
function hideSubMenu(childDivId,parentId){
	window.clearTimeout(showSubMenu.timer);	
	$("#"+childDivId).css("display","none");	
	$("#"+parentId).removeClass("navHovered");
}
function goFront(){
	
}

function performGA(gaTagId, pageName){
	
	try 
	{
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		
		var pageTracker = _gat._getTracker(gaTagId);
	
		pageTracker._setDomainName("none");
	
		pageTracker._setAllowLinker(true);
	
		pageTracker._setAllowHash("false");
	
		pageTracker._link();
		
		pageTracker._linkByPost();
		
		pageTracker._trackPageview();
		
	} catch(err) 
	{
	}
	
}


function emptyTextArea()
{
	var text = document.getElementById('faqTextArea').value;
	if(document.getElementById('faqTextArea').value.length !=text.replace(/^\s+|\s+$/g,"").length){
		document.getElementById('faqTextArea').value = text.replace(/^\s+|\s+$/g,"");
		document.getElementById('faqTextArea').focus();
	}
	
}
function hideAllSelectBoxes(){

	var selBox = document.getElementsByTagName("select");
		
	for(i=0;i<selBox.length;i++)
	{
		$("#"+selBox[i]).css("visibility","hidden");
				
	}

}
function showAllSelectBoxes(){
	
	var selBox = document.getElementsByTagName("select");

	for(i=0;i<selBox.length;i++)
	{
		$("#"+selBox[i]).css("visibility","visible");		
		
	}
	
}
function resetCollectionPoint(url){
	
	$.ajax(
			{
				url: url+"/AppServlet?m=CollectionPointCtrl.resetCollectionPoint",  
		    	cache: false, 
		    	error: function(xhrobj,textStatus, errorthrown){
		    	   	alert('ajax failed'+errorthrown);
				},   
				success: function(data) {
				
				   $('#panelPickup').html(data);
					//executeNoSessionScript();
				
				   
				}
			}
			
		);
	
}

function showHoursPopup(childDivId){
	
	var parentId = childDivId +"parent";
	
	var overlay1 = new YAHOO.widget.Overlay(
		childDivId,
		{
			context:[parentId,"br","tr",["beforeShow", "windowResize"]]
			,iframe:false
		}
	);
	$("#"+childDivId).css("display","block");
		
	overlay1.render();
}

function hideHoursPopup(id){
	
	$("#"+id).css("display","none");
}

/*
function executeNoSessionScript(){
	
	var noSession = document.getElementById('noSession');
		
	if(noSession == null){
		return;
	}else{
		var scrptArray = noSession.getElementsByTagName("script");

		for(i=0;i<scrptArray.length;i++)
		{
			eval( scrptArray[i].innerHTML );
		}
	}
}

function executeFontSetScript(){
	
	var fontSet = document.getElementById('fontSet');
		
	if(fontSet == null){
		return;
	}else{
		var scrptArray = fontSet.getElementsByTagName("script");

		for(i=0;i<scrptArray.length;i++)
		{
			eval( scrptArray[i].innerHTML );
		}
	}
}
*/
function setZoom() {

	document.body.style.zoom = 1;
	
}


function setOverlayWidth(id, width, height){
	
	var xpos = (pageWidth() - width)/ 2;
	if(xpos < 0) {
		xpos = 0;
	}
	//var ypos = (pageHeight() - height)/ 2;
	//if(ypos < 0) {
	//	ypos = 0;
	//}
	
	//	xpos = (xpos*0.06)+4;
	//	xpos='-'+xpos+'em';
		
	//	ypos = ypos*0.06;
	//	ypos = ypos+'em';
		
		$('#'+id).css("margin-left", -( width / 2) );
		
		//width = width * 0.06;
		
		$('#'+id).width(width+'px');
	
}

if (typeof cljs == "undefined") { var cljs = {}; }

cljs.initialize = function(o, selector, options){
    jQuery(selector).each(
        function(){
            var c = new o( this, options );
            if (typeof c.controllerName != 'undefined'){
                this[c.controllerName] = c;
            }
        }
        );
}

cljs.Spinner = {
    initialize: function(el, options){
        if(!jQuery(el)){
            return null;
        }
        jQuery(el).unbind();
        this.options = jQuery.extend(
        {
            min:null,
            max:null,
            step:1,
            maxMess:'',
            spinClass:null,
            upClass:'up',
            downClass:'down',
            maxClass:'maxReached',
            minClass:'minReached',
            delay:300,
            interval:400,
            _btn_width: 18,
            _btn_height: 14,
            _direction: null,
            _delay: 1,
            _repeat: 1
        }, options || { });
        if(this.options.spinClass){
            jQuery(el).addClass(this.options.spinClass);
        }

        if(jQuery(el).val()==this.options.min){
            jQuery(el).addClass(this.options.minClass);
        }
        if(jQuery(el).val()==this.options.max){
            jQuery(el).addClass(this.options.maxClass);
        }
        jQuery(el).mousemove(function(e){
            cljs.Spinner.onMouseMove(e,this);
        });
        jQuery(el).mouseover(function(e){
            cljs.Spinner.onMouseMove(e,this);
        });
        jQuery(el).mouseout(function(e){
            cljs.Spinner.onMouseMove(e,this);
        });
        jQuery(el).dblclick(function(e){
            cljs.Spinner.onMouseDown(e,this);
        });
        jQuery(el).click(function(e){
            cljs.Spinner.onMouseDown(e,this);
        });
        jQuery(el).mouseup(function(){
            cljs.Spinner.onMouseUp(this);
        });
        jQuery(el).keydown(function(e){
            cljs.Spinner.onKeyDown(e,this);
        });
        jQuery(el).keyup(function(e){
            cljs.Spinner.onKeyUp(e,this);
        });
        //jQuery(el).change(function(){cljs.Spinner.onChange(this);});
        cljs.Spinner.adjustValue(0,el);
    },

    onMouseUp:function(ev){
        // Cancel repeating adjustment
        window.clearInterval(this.options._repeat);
        window.clearTimeout(this.options._delay);
    },

    onMouseDown:function(e,ev){
        if(e.type != "click" && !jQuery.browser.msie){
            return;
        }; // Cancel double click, has click before double click (IE)
        var options = jQuery(ev).get(0)._spinnerOptions;
        if (this.options._direction == 0)
            return;
        var self = this;
        var adjustSelf = function() {
            self.adjustValue(self.options._direction * options.step,ev);
        };
        adjustSelf();
    },

    onKeyDown : function(e, ev) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        var options = jQuery(ev).get(0)._spinnerOptions;
        switch (key) {
            case 38 :
                this.adjustValue(options.step, ev);
                return false;
                break;
            case 40 :
                this.adjustValue(-options.step, ev);
                return false;
                break;
        }
    },
    onKeyUp : function(e, ev) {
        var v = jQuery(ev).val();
        if(!isNaN(v)){
            if (v == this.options.max) {
                jQuery(ev).addClass(this.options.maxClass);
                this.showMaxMessage(ev);
            } else {
                if (jQuery(ev).hasClass(this.options.maxClass)) {
                    jQuery(ev).removeClass(this.options.maxClass);
                    this.hideMaxMessage();
                }
            }
            if (v == this.options.min) {
                jQuery(ev).addClass(this.options.minClass);
            } else {
                if (jQuery(ev).hasClass(this.options.minClass)) {
                    jQuery(ev).removeClass(this.options.minClass);
                }
            }
        }
    },
    onChange:function(ev){
        this.adjustValue(0,ev);
    },

    adjustValue: function(i,ev){
        var vi = jQuery(ev).val().replace(/,/,".");
        var v = (isNaN(vi)) ? isNaN(parseInt(vi))?1:parseInt(vi) : Number(vi) + Number(i);
                
        var options = jQuery(ev).get(0)._spinnerOptions;
        if (options.min !== null) {
            v = Math.max(v, options.min);		        	
        }
        if (options.max !== null) {
            v = Math.min(v, options.max);
        }
        if (v == options.max) {
            jQuery(ev).addClass(this.options.maxClass);
            this.showMaxMessage(ev);
        } else {
            if (jQuery(ev).hasClass(this.options.maxClass)) {
                jQuery(ev).removeClass(this.options.maxClass);
                this.hideMaxMessage();
            }
        }
        if (v == options.min) {
            jQuery(ev).addClass(this.options.minClass);
        } else {
            if (jQuery(ev).hasClass(this.options.minClass)) {
                jQuery(ev).removeClass(this.options.minClass);
            }
        }
        // bugfix for doubles 
        // and leave trailing zero's
                
        v = String(Math.round(v * 10000)/10000);
        
        
        if(vi.indexOf(".")>=0 && v.indexOf(".")<0) v += ".0";
        if(v.indexOf(".")>=0){ while(v.length < vi.length) v += "0"; }
        
        
        
        jQuery(ev).val(v.replace(".",","));
    },

    onMouseMove:function(e,ev){
        var of = jQuery(ev).offset();//[top, left]
        var ofX = Math.round(of.left);
        var ofY = Math.round(of.top);
        //
        if(e.type == 'mouseout'){
            jQuery(e.target).removeClass('jHover');
        } else {
            var overSpinnerButton = e.pageX >= ofX + jQuery(ev).outerWidth() - this.options._btn_width;
            overSpinnerButton ? jQuery(e.target).addClass('jHover') : jQuery(e.target).removeClass('jHover');
        }
        //
        var direction = (e.pageX > ofX + jQuery(ev).outerWidth() - this.options._btn_width) ? ((e.pageY < ofY + this.options._btn_height) ? 1 : -1) : 0;
        this.options._direction = direction;
    },

    showMaxMessage: function(ev){
        var objParent = jQuery(ev).parent();
        if(jQuery(objParent).find('div.spinnerMaxReached').length == 0){
            var sm = jQuery('<div />').addClass('spinnerMaxReached');
            var msg = jQuery('<p/>').text(this.options.maxMess);
            var arrow = jQuery('<div />').addClass('arrow');

            sm.append(msg);
            sm.append(arrow);
            sm.css('left', '0px');
            jQuery(sm).appendTo(jQuery(objParent));
            setTimeout(function(){
                jQuery('div.spinnerMaxReached').fadeOut(1000);
            },2000);
        }else{
            var sm = jQuery(objParent).find('.spinnerMaxReached');
            sm.css('left','0px');
            jQuery(objParent).find('.spinnerMaxReached').css('display','block');
            setTimeout(function(){
                jQuery('div.spinnerMaxReached').fadeOut(1000);
            },2000);
        }
    },

    hideMaxMessage: function(){
        if(jQuery(document).find('div.spinnerMaxReached')){
            jQuery(document).find('div.spinnerMaxReached').remove();
        }
    }
}

/*
cljs.SpinnerManagerOLD = {
    initPage: function(){
    	jQuery('.product,.productDetail,.prodActions').find('.order').each(
	    	function(){
	    		var 
	    		val,
	    		opts = {
					min: 1,
					max: 9999,
					step: 1
	    		},
	    		customSteps = { 0:1, G:0.1 },
	    		spinner = $(this).find(":text"),
	    		callback = function(evt){
		        	val = $(this).val() || "S";
		        	spinner.val( String(spinner.val()).replace(/[^0-9\.]/,"") );
		        	
		        	opts.step = getStep(spinner.val() || 0);
		        	opts.min = opts.step;
		        	// whole numbers if not in weight
		        	if(val != "G") { spinner.val( Math.round( spinner.val() || 0 ) ); }
	            };
	    		$(this).find(":text").each(
		            function(el){
		                jQuery(this).attr('autocomplete','off');
		                this._spinnerOptions = opts;
		                cljs.Spinner.initialize(this,opts);
		            }
		        );
		        // change step on weightCode change
		        $(this).find("select").each(callback).change(callback);
	    	}
    	);
    	
    }
};
*/

cljs.SpinnerManager = {
    initPage: function(){
		jQuery('.product,.productDetail,.prodActions,#changeQuantity').find('.order').each(
	    	function(){
	    		var 
	    		val,
	    		opts = {
						min: 0,
						max: 9999,
						step: 1
	    		},
	    		spinner = $(this).find(":text"),
	    		dropdown = $(this).find("select"),
	    		changeDropDown = function(){
	    			val = spinner.val();
		        	// whole numbers if not in weight
		        	if((dropdown.val() || "S") != "G") { 
		        		if(val!="0") spinner.val( parseInt(val) || 1); 
		        		opts.step = 1;
		        	}else {
			        	var i = parseInt(val);
		        		if(val.charAt(val.length-1)== "." ||  val.length==String(i).length || val=="") {
		    					opts.step = 1;
		    				}else{
		    					if(val.charAt(0) == ".") val = "0" + val;
		    					opts.step =  1/Math.pow(10, val.length - String((i||0)).length - 1);
		    				}
		        	}
		        	opts.min = opts.step;
	            };
	    		spinner.each(
		            function(index, el){
		            		// replace 1000-separator
		            		var t = $(this); t.val(t.val().replace(".",""));
		                jQuery(this).attr('autocomplete','off');
		                this._spinnerOptions = opts;
		                cljs.Spinner.initialize(this,opts);
		            }
		        );
		        // change step on weightCode change
		        dropdown.each(changeDropDown).change(changeDropDown);
		        spinner.keyup(changeDropDown).mouseup(changeDropDown);
	    	}
    	);
    	
    }
};

function initRecommendedQtys()
{
	$("div.recommendedAmount a").click(function(evt){
		evt.preventDefault();
		
		var 
			me 		= $(this),
			txt 	= me.text(),
			prod	= me.parentsUntil(".product").parent(),
			order	= prod.find(".order form")
		;
		order	
			.find(":text")
			.val(txt.match(/[0-9\.,]*/));
		order
			.find("select")
			.val({
				kg:"G",
	  		st:"S",
	  		pc:"S" 
			}[txt.match(/[A-Za-z]+/)]);				
	});
}

function requestOpenHours(url, collectionIndex, forDateNTime){
	
	var indexx = "hidden"+collectionIndex;
	if(document.getElementById(indexx)!=null && document.getElementById(indexx).value!=null){
		var collectionDay = document.getElementById(indexx).value;
		var selectedOption = $('#selectDate option:selected').attr('id');
	}
	if(document.getElementById('poco')!=null && document.getElementById('poco').value!=null){
		var searchText = document.getElementById('poco').value;	
	}
	var ctrlMethod = '/AppServlet?m=CollectionPointCtrl.prepareOpenHours&ts='+new Date().getTime()+'&selectedCollectionDay='+collectionDay+'&forDateNTime='+forDateNTime;
	
	showCollectionPointPopup(url,ctrlMethod,'',searchText);
	if(selectedOption!=null || selectedOption!=""){	
		$("#"+selectedOption).ready(function(){
			window.setTimeout(function(){$("#"+selectedOption).attr("selected","selected") ; },500);
		});
	}
}

function call(url){
	$('#include-from-outside').load(url);
	}
      		  
$(function(){
	$('#tabMenu li').click(function(e){
		$('#tabMenu li').removeClass('active'); 
		$(this).addClass('active');
	});
});

$(document).ready(function() {
    try{ cljs.SpinnerManager.initPage(); }catch(err){}
    try{ initRecommendedQtys(); }catch(err){}
});

