var windowG;
var excludeIDList;

Number.prototype.formatCurrency = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

/* 
 * US // 17.06.2011 - Classifieds v2
 * Funktion zum Ein-/Ausblenden von Rubriken bei der Suche
 */
function updateSearchForm() {
	var rid = document.getElementById('rubrics').options[document.getElementById('rubrics').selectedIndex].value;
	var zip = document.getElementById('zipcode').value;
	var showconditions = true;
	var showpricing = true;

	if(rid != 0 || rid != '' || !isNaN(rid)){
		registerPositionStore = new Ext.data.JsonStore({
			url: '/?event=cmp.cst.classifieds2.getrubricattributes&rid=' + rid,
			root: 'DATA',
			autoLoad: true,
			fields: ['RUBRIC'],
			listeners: {
				load: function(store, records) {
					if(records[0].data.RUBRIC){
						if(records[0].data.RUBRIC.showconditions == 0){
							document.getElementById('classifiedstate').disabled = true;
							document.getElementById('classifiedstate').selectedIndex = 0;
						} else {
							document.getElementById('classifiedstate').disabled = false;
							document.getElementById('classifiedstate').selectedIndex = 0;
						}
						if(records[0].data.RUBRIC.showpricing == 0){
							document.getElementById('maxpricelimit').disabled = true;
							document.getElementById('maxpricelimit').selectedIndex = 0;
						} else {
							document.getElementById('maxpricelimit').disabled = false;
							document.getElementById('maxpricelimit').selectedIndex = 0;
						}
					} else {
						document.getElementById('classifiedstate').disabled = false;
						document.getElementById('classifiedstate').selectedIndex = 0;
						document.getElementById('maxpricelimit').disabled = false;
						document.getElementById('maxpricelimit').selectedIndex = 0;
					}
				}
			}
		});
	};
	// umkreissuche ausblenden, solange keine plz angegeben wurde
	if(!isNaN(zip) && zip.length > 4){
		document.getElementById('radialsearch').disabled = false;
	}else{
		document.getElementById('radialsearch').disabled = true;
		document.getElementById('radialsearch').selectedIndex = 0;
	}
}

function confirmDelInvoiceAddr(title,msg,id){
	var registerPositionStore;
	
	//Show a dialog using config options:
	Ext.Msg.show({
	   title: title,
	   msg: msg,
	   buttons: Ext.Msg.YESNO,
	   fn: function(btn){
		   if(btn == 'yes'){
			   registerPositionStore = new Ext.data.JsonStore({
					url: '/?event=cmp.cst.classifieds2.delinvoiceaddress&random=' + Math.random(),
					root: 'DATA',
					autoLoad: true,
					fields: ['FORM', 'SUCCESSFULLYSENT'],
					baseParams: {
						'cmp.cst.classifieds2.id': id
					},
					listeners: {
						load: function(store, records) {
							for(var i=0;i<records.length; i++){	
								if(records[i].data.SUCCESSFULLYSENT.CODE && document.getElementById('differinvoicebox') != null){
									document.getElementById('differinvoicebox').innerHTML = '';
									document.getElementById('differinvoicebox').innerHTML = records[i].data.SUCCESSFULLYSENT.RESULT;
								}					
							}	
							windowG.center();
						}			
					}
				}); 
		   } else {}
	   },
	   animEl: 'elId',
	   cls: 'msgbox'
	});
}

/* Abweichende Rechnungsadresse - Formular - Popup */
function showInvoiceaddrForm(id) {
	
	if (windowG) {
		windowG.destroy();
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 880,
		cls: 'supportpopup',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'<div id="supportcontainer"><img src="/js/libs/ext-2.3.0/resources/images/default/shared/blue-loading.gif" alt="loading" /></div>'			
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	
	windowG.show(1, function() { loadInvoiceaddrForm('', '', '', '', '', '', '', '', '', '', 0, id); });
}
/* Abweichende Rechnungsadresse - Forumular - Popup */
function loadInvoiceaddrForm(company, companyadd, salutation, firstname, lastname, street, zipcode, city, country, taxidentnumber, send, id) {
	
	if(!company) company = "";
	if(!companyadd) companyadd = "";
	if(!salutation) salutation = "";
	if(!firstname) firstname = "";
	if(!lastname) lastname = "";
	if(!street) street = "";
	if(!zipcode) zipcode = "";
	if(!city) city = "";
	if(!country) country = "";
	if(!taxidentnumber) taxidentnumber = "";
	if(!send) send = 0;

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getinvoiceaddrform&random=' + Math.random(),
		root: 'DATA',
		autoLoad: true,
		fields: ['FORM', 'SUCCESSFULLYSENT'],
		baseParams: {
			company: company,
			companyadd: companyadd,
			salutation: salutation,			
			firstname: firstname,
			lastname: lastname,
			street: street,
			zipcode: zipcode,
			city: city,
			country: country,
			taxidentnumber: taxidentnumber,
			send: send,
			'cmp.cst.classifieds2.id': id
		},
		listeners: {
			load: function(store, records) {
				for(var i=0;i<records.length; i++){					
					document.getElementById('supportcontainer').innerHTML = records[i].data.FORM;
					if(records[i].data.SUCCESSFULLYSENT.CODE) {
						windowG.close();
						document.getElementById('differinvoicebox').innerHTML = records[i].data.SUCCESSFULLYSENT.RESULT;
					}
				}
				setBindsOnStep30Layer();
				setMandatoryOnStep30Layer();
				windowG.center();
			}			
		}
	});
	
}
/* Abweichende Rechnungsadresse - Forumular - Popup */
function saveInvoiceForm() {

	document.getElementById('submitbutton').disabled = "disabled";
	
	loadInvoiceaddrForm(
		document.getElementById('company_i').value,
		document.getElementById('companyadd_i').value,
		getCheckedValue(document.forms['invoiceaddress'].elements['salutation_i']),
		document.getElementById('firstname_i').value,
		document.getElementById('lastname_i').value,
		document.getElementById('street_i').value,
		document.getElementById('zipcode_i').value,
		document.getElementById('city_i').value,
		document.getElementById('country_i').options[document.getElementById('country_i').selectedIndex].value,
		document.getElementById('taxidentnumber_i').value,
		1,
		document.getElementById('classifiedid').value
	);
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	var vals = "";
	
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			if(vals.length == 0){
				vals = radioObj[i].value;
			}else{
				vals += ',' + radioObj[i].value;
			}
		}
	}
	
	return vals;
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function reloadStep10Prices(){
	
	var elco = document.forms['formstep10'].elements['classifiedoffer'];
	var valco = getCheckedValue(elco).toString();
	
	var elcoa = document.forms['formstep10'].elements['classifiedofferadds'];
	var valcoa = getCheckedValue(elcoa).toString();
	
	var sum = 0;
	var items = valcoa.split(',');
	
	if(valco != ''){
		document.getElementById('choice_coname').innerHTML = o[valco].name;
		document.getElementById('choice_coprice').innerHTML = o[valco].price.formatCurrency(2, ',', '.') + '&nbsp;&euro;';
		sum += o[valco].price*1;
	}
	// clear old stuff
	document.getElementById('choice_coaname').innerHTML = '';
	document.getElementById('choice_coaprice').innerHTML = '';
	
	// even if volca is empty, items got an empty strings
	if(items[0] != ''){
		for(var x=0; x < items.length; x++){
			if(x == 0){
				document.getElementById('choice_coaname').innerHTML = o[valco].adds[items[x]].name;
				document.getElementById('choice_coaprice').innerHTML = o[valco].adds[items[x]].price.formatCurrency(2, ',', '.') + '&nbsp;&euro;';	
			} else {
				document.getElementById('choice_coaname').innerHTML += '<br/>' + o[valco].adds[items[x]].name;
				document.getElementById('choice_coaprice').innerHTML += '<br/>' + o[valco].adds[items[x]].price.formatCurrency(2, ',', '.') + '&nbsp;&euro;';
			}
			sum += o[valco].adds[items[x]].price*1;
		}
	}
	// get summary
	document.getElementById('choice_pricesum').innerHTML = sum.formatCurrency(2, ',', '.') + '&nbsp;&euro;';
}

function setBoxesOnStep10(initial) {

	var elco = document.forms['formstep10'].elements['classifiedoffer'];
	var valco = getCheckedValue(elco).toString();
	var initial = typeof(initial) == 'number' ? 1 : 0;
	
	if(valco != ''){
		Ext.select("input[name=classifiedoffer]").each(function(item){
			hideContent('classifiedofferadd_'+ item.dom.id.split("_")[1]);
			hideContent('classifiedoffernotice_'+ item.dom.id.split("_")[1]);
			if(initial == 0){
				// dies nur machen, wenn die funktion nicht initial (das erste mal) aufgerufen wurde!
				Ext.select("input[name=classifiedofferadds]").each(function(item){
					item.dom.checked=false;
				})
			}
		});
		showContent('classifiedofferadd_'+valco);
		showContent('classifiedoffernotice_'+valco);
		Ext.each(document.forms['formstep10'].elements['classifiedofferadds'], function(item){item.disabled = false});
	} else {
		Ext.each(document.forms['formstep10'].elements['classifiedoffer'], function(item){hideContent('classifiedoffernotice_'+ item.value);});
		Ext.each(document.forms['formstep10'].elements['classifiedofferadds'], function(item){item.disabled = true});
	}
	// pricebox init
	reloadStep10Prices();
}

function setBindsBoxesOnStep10(){
	Ext.select("input[name=classifiedoffer]").each(function(item){
		item.on('click',setBoxesOnStep10,false);
		item.on('click',reloadStep10Prices,false);
	})
	Ext.select("input[name=classifiedofferadds]").each(function(item){
		item.on('click',reloadStep10Prices,false);
	})
}

function setBoxesOnStep20() {

	var elpt = document.forms['formstep20'].elements['pricetype'];
	var valpt = getCheckedValue(elpt).toString();
	
	var elchipher = document.getElementById('chipher');
	
	if(valpt != '' && (valpt == 1 || valpt == 7)){
		document.getElementById('price').value = '0,00';
		document.getElementById('price').disabled = true;
		document.getElementById('pricelabelmandatoryicon').innerHTML = '';
	} else {
		document.getElementById('price').disabled = false;
		document.getElementById('pricelabelmandatoryicon').innerHTML = '*';
	}
	
	if(elchipher != null && elchipher.checked == true){
		showContent('chipherbox');
		hideContent('contactbox');
	} else {
		showContent('contactbox');
		hideContent('chipherbox');
	}
}

function setBindsBoxesOnStep20(){
	Ext.select("input[name=pricetype]").each(function(item){
		item.on('click',setBoxesOnStep20,false);
	})
	
	var elchipher = Ext.get('chipher');
	if(elchipher != null){
		elchipher.on('click',setBoxesOnStep20,false);
	}
}

function updateInputsByRubrics() {
	var rids = document.getElementById('rubrics').value;

	var showconditions = true;
	var showpricing = true;

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getrubricattributes&rids=' + rids,
		root: 'DATA',
		autoLoad: true,
		fields: ['RUBRICS'],
		listeners: {
			load: function(store, records) {
				var elcondition = document.forms['formstep20'].elements['condition'];
				var elpricetype = document.forms['formstep20'].elements['pricetype'];

				showconditions = records[0].data.RUBRICS.globalShowConditions;
				showpricing = records[0].data.RUBRICS.globalShowPricing;
				
				if(showconditions == false){
					setCheckedValue(elcondition, '3');
					hideContent('conditionbox');
				} else {
					showContent('conditionbox');
				}
				
				if(showpricing == false){
					setCheckedValue(elpricetype, '3');
					hideContent('pricetypebox');
					document.getElementById('price').value = 0;
					hideContent('pricebox');
				} else {
					showContent('pricetypebox');
					showContent('pricebox');
				}
			}
		}
	});
}


function setBoxesOnStep30() {
	// lastschriftverfahren
	var elcountry = document.getElementById('country');
	var valcountry = elcountry.options[elcountry.selectedIndex].value.toString();

	var elpaymentmethod = document.forms['formstep30'].elements['paymentmethod'];
	var valpaymentmethod = getCheckedValue(elpaymentmethod).toString();
	// 57 = Deutschland! Diese Box gibt es nur fuer Inlandskunden
	if(valcountry != '' && valcountry == 57){
		showContent('directdebitingsystem_box');
		document.getElementById('taxidentnumbermandatoryicon').innerHTML = "";
	}else{
		hideContent('directdebitingsystem_box');
		document.getElementById('taxidentnumbermandatoryicon').innerHTML = "*";
		if(valpaymentmethod == 2)
			setCheckedValue(elpaymentmethod, '0');
	}
	// felder von lastschriftverfahren
	if(valpaymentmethod != '' && valpaymentmethod == 2){
		showContent('directdebitingsystem_inputs');
	}else{
		hideContent('directdebitingsystem_inputs');		
	}
	
	if(valpaymentmethod != '' && valpaymentmethod == 1){
		showContent('invoice_inputs');
	}else{
		hideContent('invoice_inputs');
	}
}

function setBindsBoxesOnStep30(){
	var elcountry = Ext.get('country');
	var elpayment_direct = Ext.get('paymentmethod_directdebitingsystem');
	var elpayment_invoice = Ext.get('paymentmethod_invoice');
	
	elcountry.on('change',setBoxesOnStep30,false);
	elpayment_direct.on('click',setBoxesOnStep30,false);
	elpayment_invoice.on('click',setBoxesOnStep30,false);
}

function setBoxesOnPrintClassifieds() {
	
	var elclassifiedsource = document.forms['printclassified'].elements['classifiedsource'];
	var valclassifiedsource = getCheckedValue(elclassifiedsource).toString();
	
	var elcontactmethod = document.forms['printclassified'].elements['contactmethod'];
	var valcontactmethod = getCheckedValue(elcontactmethod).toString();	
	
	
	// felder fuer anzeigenquelle
	if(elclassifiedsource != '' && valclassifiedsource == '1'){
		showContent('classifiedsource_txtpics_box');
	}else{
		hideContent('classifiedsource_txtpics_box');		
	}
	if(elclassifiedsource != '' && valclassifiedsource == '2'){
		showContent('classifiedsource_pdf_box');
	}else{
		hideContent('classifiedsource_pdf_box');		
	}
	
	// kontaktmethode -> mail
	if(elcontactmethod != '' && valcontactmethod == '1'){
		showContent('contactmethod_mail_box');
	}else{
		hideContent('contactmethod_mail_box');		
	}
	// kontaktmethode -> telefon
	if(elcontactmethod != '' && valcontactmethod == '2'){
		showContent('contactmethod_phone_box');
	}else{
		hideContent('contactmethod_phone_box');		
	}
	// kontaktmethode -> post
	if(elcontactmethod != '' && valcontactmethod == '3'){
		showContent('contactmethod_post_box');
	}else{
		hideContent('contactmethod_post_box');		
	}
}

function setBindsBoxesOnPrintClassifieds(){
	var el1 = Ext.get('classifiedsource_txtpics');
	var el2 = Ext.get('classifiedsource_pdf');
	var el3 = Ext.get('contactmethod_mail');
	var el4 = Ext.get('contactmethod_phone');
	var el5 = Ext.get('contactmethod_post');
	
	el1.on('click',setBoxesOnPrintClassifieds,false);
	el2.on('click',setBoxesOnPrintClassifieds,false);
	el3.on('click',setBoxesOnPrintClassifieds,false);
	el4.on('click',setBoxesOnPrintClassifieds,false);
	el5.on('click',setBoxesOnPrintClassifieds,false);
}

function hideContent(id){
	var el = document.getElementById(id);
	
	if(el != null){
		el.style.display = 'none';
	}
}

function showContent(id){
	var el = document.getElementById(id);
	
	if(el != null){
		el.style.display = 'block';
	}
}

function toggleContent(id){
	var el = document.getElementById(id);
	
	if(el != null){
		if(el.style.display == 'none'){
			el.style.display = 'block';
		} else {
			el.style.display = 'none';
		}
	}
}

function addToWatchlist(id,elthis) {
	Ext.Ajax.request({
		url: '/index.cfm?event=cmp.cst.classifieds2.addtowatchlist',
		params: {
			'cmp.cst.classifieds2.pk': id
		},
		method: 'POST',
		success: function(resp) {
		    // resp ist das XmlHttpRequest-Object
		    var jsonData = Ext.decode(resp.responseText);
		    var elcontent = document.getElementById('myWatchlistCount');
		    
		    Ext.Msg.show({
				title: jsonData.title,
				msg: jsonData.message,
				buttons: Ext.Msg.OK,						   
				animEl: 'elId',
				cls: 'msgbox'
			});	
		    
		    if(elcontent && jsonData.error == 0){
		    	txtcontent = elcontent.innerHTML;
		    	var number = txtcontent.substring(1,txtcontent.length-1);
		        if(!isNaN(number)){
		            number++;
		            elcontent.innerHTML = '(' + number + ')';
		        }
		        Ext.get(elthis).set({'class':'rem_notice','title':jsonData.labeltext.removeclassified,'onclick':'removeClassifiedFromWatchlist('+id+',this);return false;'});
		        Ext.get(elthis).dom.innerHTML = jsonData.labeltext.removeclassified;
		    }
		},
		failure: function() {}
	});
};

function removeClassifiedFromWatchlist(ids,elthis) {
	var i = 0;
	Ext.Ajax.request({
		url: '/index.cfm?event=cmp.cst.classifieds2.removeclassifiedsfromwatchlist',
		params: {
			pks: ids
		},
		method: 'POST',
		success: function(resp) {
		    // resp ist das XmlHttpRequest-Object
		    var jsonData = Ext.decode(resp.responseText);
		    var elcontent = Ext.get('myWatchlistCount');
		    var doReload = false;
		    
		    if(jsonData.error == 0){
		    	if(jsonData.ids.length !== Ext.query('*[id^=classifieditem].item').length){
		    		// slideout the specific elements!
		    		for (i = 0; i < jsonData.ids.length; i++){
				    	try{
							Ext.get('classifieditem'+jsonData.ids[i]).slideOut('t', {
								easing: 'easeOut',
								duration: .8,
								remove: true,
								useDisplay: true
							});
				    	}
				    	catch(e){}
					}
		    	}else{
		    		// empty list => show other content!
		    		Ext.fly('watchlistcontent').update(''+
		    		'<div class="classified_ad" id="watchlistcontent">'+
		    		'	<h1>Zurzeit sind keine Anzeigen auf Ihrer Merkliste vorhanden.</h1>'+
			    	'	<div class="ad_detail">'+
			    	'		<div class="back">'+
		    		'			<a onclick="history.back();return false;" href="#" title="Zur&uuml;ck">Zur&uuml;ck</a>'+
			    	'		</div>'+
			    	'	</div>'+
			    	'</div>');
		    	}
		    }
		    
		    // show resultmessagebox
		    Ext.Msg.show({
				title: jsonData.title,
				msg: jsonData.message,
				buttons: Ext.Msg.OK,
				animEl: 'elId',
				cls: 'msgbox'
			});

		    // refresh toolbarstati
		    if(elcontent && jsonData.error == 0){
		    	var txtcontent = elcontent.dom.innerHTML;
		    	var number = txtcontent.substring(1,txtcontent.length-1);
		        if(!isNaN(number)){
		            number--;
		            elcontent.dom.innerHTML = '(' + number + ')';
		        }
		        if(elthis){
			        Ext.get(elthis).set({'class':'ad_notice','title':jsonData.labeltext.addclassified,'onclick':'addToWatchlist('+ids+',this);return false;'});
			        Ext.get(elthis).dom.innerHTML = jsonData.labeltext.addclassified;
		        }
		    }
		},
		failure: function() {}
	});
};

function checkAll(exby) {
	var tiny = document.getElementsByName("classifieds");	
	for (i = 0; i < tiny.length; i++) {
		tiny[i].checked = exby.checked? true:false
	}
}

function resetCheckboxes(el) {
	var tiny = document.getElementsByName('document.files.teaserimage');
	for (i = 0; i < tiny.length; i++){
		if(el.value != tiny[i].value){
			tiny[i].checked = false;
		}
	}
}

function WatchListActions(){
	var index = Ext.get('watchlistactions').dom.selectedIndex;
	var tiny = document.watchlist.classifieds;
	var pks = '';
	
	/* fetch all checked checkboxes -> save in pks */
	for (i = 0; i < tiny.length; i++){
		if(tiny[i].type == 'checkbox' && tiny[i].checked == true){
            if(pks.length)
                pks = pks + ",";
			pks = pks + tiny[i].value;
		}
	}
	
	/* if just one checkbox is in form! then it is not an array! Just an Element */
	if(typeof(document.watchlist.classifieds.length)=="undefined" && document.watchlist.classifieds.checked){
	    pks = document.watchlist.classifieds.value;
	}
	
	/* at this point! */
	/* if pks is empty, so no checkbox is checked! no matter its 1 or more than 1 checkboxes! /* 
		
	/* evalate the index of dropdownbox -> actions */
	f = Ext.get('watchlistactions');
	f.removeClass('selectboxred');		
	switch (index) {
		case 0:			
			f.addClass('selectboxred');			
			break;
		 
		case 1: 
			/* delete all checked classifieds */
			removeClassifiedFromWatchlist(pks);
			break;
		 
		case 2:
			/* print all checked classifieds */
			if(pks.length > 0)
			{
				var url = "/index.cfm?event=cmp.cst.classifieds2.print&classifieds.ids=" + pks;
				popup(url, 'DruckansichtKleinanzeigen', 700, 800);
			}
			else
			{
				Ext.Msg.show({
					title: 'Hinweis',
					msg: 'Es wurden keine Anzeigen markiert.',
					buttons: Ext.Msg.OK,						   
					animEl: 'elId',
					cls: 'msgbox'
				});	
			}
			break;
		 
		case 3:
			/* recommend all checked classifieds */
			if(pks.length > 0)
			{
				showRecommendForm('Anzeigen-Empfehlung von www.dhz-anzeigenmarkt.de', pks);
			}
			else
			{
				Ext.Msg.show({
					title: 'Hinweis',
					msg: 'Es wurden keine Anzeigen markiert.',
					buttons: Ext.Msg.OK,						   
					animEl: 'elId',
					cls: 'msgbox'
				});				
			}
			break;
		 
		default:
			break;
	}
}
/* Print it! */
function printClassifieds(ids,mine){
	if(!mine){
		mine = 0;
	}
    var url = "/index.cfm?event=cmp.cst.classifieds2.print&classifieds.ids=" + ids + "&cmp.cst.classifieds2.mine=" + mine;
    popup(url, 'print', 700, 800);
}

/* Print it! */
function printStep(id){

	var url = "/index.cfm?event=cmp.cst.classifieds2.printstep&classifieds.id=" + id;
    popup(url, 'print', 700, 800);
}

/* Weiterempfehlen - Formular - Popup */
function showRecommendForm(subject, id) {
	
	if (windowG) {
		windowG.destroy();
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 880,
		cls: 'supportpopup',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'<div id="supportcontainer"><img src="/js/libs/ext-2.3.0/resources/images/default/shared/blue-loading.gif" alt="loading" /></div>'			
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	
	windowG.show(1, function() { loadRecommendForm(subject, '', '', '', '', '', 0, id); });
	
}
/* Weiterempfehlen - Forumular - Popup */
function loadRecommendForm(subject, sender, receiver, message, captcha, captchacrypt, send, id) {
	
	if(!subject) subject = "";
	if(!sender) sender = "";
	if(!receiver) receiver = "";
	if(!message) message = "";
	if(!captcha) captcha = "";
	if(!captchacrypt) captchacrypt = "";
	if(!send) send = 0;
	if(!id) id = 0;

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getrecommendform&random=' + Math.random(),
		root: 'DATA',
		autoLoad: true,
		fields: ['FORM', 'SUCCESSFULLYSENT'],
		baseParams: {
			subject: subject,
			sender: sender,
			receiver: receiver,			
			message: message,
			captcha: captcha,
			captchacrypt: captchacrypt,
			send: send,
			id: id
		},
		listeners: {
			load: function(store, records) {
				for(var i=0;i<records.length; i++){					
					document.getElementById('supportcontainer').innerHTML = records[i].data.FORM;
					if(records[i].data.SUCCESSFULLYSENT.CODE) {
						windowG.close();
						Ext.Msg.show({
							title: records[i].data.SUCCESSFULLYSENT.TITLE,
							msg: records[i].data.SUCCESSFULLYSENT.MESSAGE,
							buttons: Ext.Msg.OK,						   
							animEl: 'elId',
							cls: 'msgbox'
						});
					}
				}	
				
				windowG.center();
			}			
		}
	});
	
}
/* Weiterempfehlen - Forumular - Popup */
function saveRecommendForm() {

	document.getElementById('submitbutton').disabled = "disabled";
	
	if(document.getElementById('captcha'))
		cap = document.getElementById('captcha').value;
	else
		cap = '';
	
	if(document.getElementById('captchacrypt'))
		capcr = document.getElementById('captchacrypt').value;
	else
		capcr = '';
	
	loadRecommendForm(
		document.getElementById('tsubject').value,
		document.getElementById('sender').value,
		document.getElementById('receiver').value,
		document.getElementById('message').value,
		cap,	
		capcr,
		1,
		document.getElementById('id').value
	);
}

function showChipherResponseForm(id, subject){
	
	if (windowG) {
		windowG.destroy();
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 880,
		cls: 'supportpopup',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'<div id="supportcontainer"><img src="/js/libs/ext-2.3.0/resources/images/default/shared/blue-loading.gif" alt="loading" /></div>'			
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	
	windowG.show(1, function() { loadChipherResponseForm(subject, '', '', '', '', '', '', '', 0, '', '', '', '', '', 0, id); });
}

function loadChipherResponseForm(subject, message, company, companyadd, contactperson, street, zipcode, city, country, phone, fax, sender, captcha, captchacrypt, send, id) {
	
	if(!subject) subject = "";
	if(!message) message = "";
	if(!company) company = "";
	if(!companyadd) companyadd = "";
	if(!contactperson) contactperson = "";
	if(!street) street = "";
	if(!zipcode) zipcode = "";
	if(!city) city = "";
	if(!country) country = 0;
	if(!phone) phone = "";
	if(!fax) fax = "";
	if(!sender) sender = "";
	if(!captcha) captcha = "";
	if(!captchacrypt) captchacrypt = "";
	if(!send) send = 0;
	if(!id) id = 0;

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getChipherResponseForm&random=' + Math.random(),
		root: 'DATA',
		autoLoad: true,
		fields: ['FORM', 'SUCCESSFULLYSENT'],
		baseParams: {
			subject: subject,
			message: message,
			company: company,			
			companyadd: companyadd,
			contactperson: contactperson,
			street: street,
			zipcode: zipcode,			
			city: city,
			country: country,
			phone: phone,
			fax: fax,			
			sender: sender,
			captcha: captcha,
			captchacrypt: captchacrypt,
			send: send,
			id: id
		},
		listeners: {
			load: function(store, records) {
				for(var i=0;i<records.length; i++){

					document.getElementById('supportcontainer').innerHTML = records[i].data.FORM;
					if(records[i].data.SUCCESSFULLYSENT.CODE) {
						windowG.close();
						
						Ext.Msg.show({
							title: records[i].data.SUCCESSFULLYSENT.TITLE,
							msg: records[i].data.SUCCESSFULLYSENT.MESSAGE,
							buttons: Ext.Msg.OK,						   
							animEl: 'elId',
							cls: 'msgbox'
						});
					}
				}	
				windowG.center();
			}			
		}
	});
}

function saveChipherResponseForm() {

	document.getElementById('submitbutton').disabled = "disabled";
	
	if(document.getElementById('captcha_c'))
		cap = document.getElementById('captcha_c').value;
	else
		cap = '';
	
	if(document.getElementById('captchacrypt_c'))
		capcr = document.getElementById('captchacrypt_c').value;
	else
		capcr = '';
	
	loadChipherResponseForm(
		document.getElementById('subject_c').value,
		document.getElementById('message_c').value,
		document.getElementById('company_c').value,
		document.getElementById('companyadd_c').value,
		document.getElementById('contactperson_c').value,
		document.getElementById('street_c').value,
		document.getElementById('zipcode_c').value,
		document.getElementById('city_c').value,
		document.getElementById('country_c').value,
		document.getElementById('phone_c').value,
		document.getElementById('fax_c').value,
		document.getElementById('sender_c').value,
		cap,	
		capcr,
		1,
		document.getElementById('classifiedid').value
	);
}


function getRemainingChars(el, maxLength, labelId, e) {
	
  var label = document.getElementById(labelId);
  var rest = maxLength - el.value.length;
  var code = e.keyCode;

  if (rest <= 0
    &&(
    	code !== 18 // alt
    	&& code !== 17 // shift
	    && code !== 46 // delete
	    && code !== 8  // back space
	    && code !== 33 // pic up
	    && code !== 34 // pic down
	    && code !== 35 // end
	    && code !== 36 // pos 1
	    && code !== 37 // <- arrow
	    && code !== 38 // ^ arrow 
	    && code !== 39 // -> arrow
	    && code !== 40 // \/ arrow
	  ) 
    )
 {
   if(e.preventDefault){
	   // FF
	   e.preventDefault();
   } else {
	   // IE
	   e.returnValue = false;		   
   }
   el.value = el.value.substring(0,maxLength);
   rest = 0;	  
  }
  
  label.innerHTML = rest;
  el.scrollTop = el.scrollHeight;
}

/* Benachrichtigungsservice - Formular - Popup */
function showNotificationserviceForm(id) {
	
	if(!id || typeof(id) == 'undefined'){
		id = 0;
	}
	
	if (windowG) {
		windowG.destroy();
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 880,
		cls: 'supportpopup',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'<div id="supportcontainer"><img src="/js/libs/ext-2.3.0/resources/images/default/shared/blue-loading.gif" alt="loading" /></div>'			
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	
	windowG.show(1, function() { loadNotificationserviceForm('', '', '', '', 0, id); });
}
/* Benachrichtigungsservice - Forumular - Popup */
function loadNotificationserviceForm(email, emailconfirm, captcha, captchacrypt, send, id) {
	
	if(!email) email = "";
	if(!emailconfirm) emailconfirm = "";
	if(!captcha) captcha = '';
	if(!captchacrypt) captchacrypt = '';
	if(!send) send = 0;
	if(!id) id = 0;

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getnotificationserviceform&random=' + Math.random(),
		root: 'DATA',
		autoLoad: true,
		fields: ['FORM', 'MESSAGE'],
		baseParams: {
			email: email,
			emailconfirm: emailconfirm,
			captcha: captcha,
			captchacrypt: captchacrypt,
			send: send,
			rubric: id
		},
		listeners: {
			load: function(store, records) {
				for(var i=0;i<records.length; i++){					
					
					document.getElementById('supportcontainer').innerHTML = records[i].data.FORM;
					
					if(records[i].data.MESSAGE.CODE) {
						windowG.close();
						
						Ext.Msg.show({
							title: records[i].data.MESSAGE.TITLE,
							msg: records[i].data.MESSAGE.MESSAGE,
							buttons: Ext.Msg.OK,						   
							animEl: 'elId',
							cls: 'msgbox'
						});
					}
				}	
				windowG.center();
			}			
		}
	});
}

/* Abweichende Rechnungsadresse - Forumular - Popup */
function saveNotificationserviceForm() {

	var elrubric = document.getElementById('rubric_n');
	var cap = '';
	var capcr = '';
	
	if(document.getElementById('captcha_n'))
		cap = document.getElementById('captcha_n').value;
	
	if(document.getElementById('captchacrypt_n'))
		capcr = document.getElementById('captchacrypt_n').value;
		
	document.getElementById('submitbutton').disabled = "disabled";
	
	loadNotificationserviceForm(
		document.getElementById('email_n').value,
		document.getElementById('emailconfirm_n').value,
		cap,
		capcr,
		1,
		elrubric.options[elrubric.selectedIndex].value.toString()
	);
}

/* Benachrichtigungsservice - Formular - Popup */
function showRubricselectionForm(ids) {
	
	if (windowG) {
		windowG.destroy();
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 880,
		cls: 'supportpopup',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'<div id="supportcontainer"><img src="/js/libs/ext-2.3.0/resources/images/default/shared/blue-loading.gif" alt="loading" /></div>'			
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	
	windowG.show(1, function() { loadRubricselectionForm(0, ids); });
}
/* Benachrichtigungsservice - Forumular - Popup */
function loadRubricselectionForm(send, ids) {
	
	if(!send) send = 0;
	if(!ids) ids = '';

	registerPositionStore = new Ext.data.JsonStore({
		url: '/?event=cmp.cst.classifieds2.getrubricselectionform&random=' + Math.random(),
		root: 'DATA',
		autoLoad: true,
		fields: ['FORM', 'SUCCESSFULLYSENT'],
		baseParams: {
			send: send,
			ids: ids
		},
		listeners: {
			load: function(store, records) {
				for(var i=0;i<records.length; i++){					
					
					document.getElementById('supportcontainer').innerHTML = records[i].data.FORM;
					
					if(records[i].data.SUCCESSFULLYSENT.CODE) {
						windowG.close();
						document.getElementById('rubricsbox').innerHTML = records[i].data.SUCCESSFULLYSENT.RESULT;
						document.getElementById('rubrics').value = records[i].data.SUCCESSFULLYSENT.RESULTIDS;
						updateInputsByRubrics();
					}
				}	
				windowG.center();
			}			
		}
	});
	
}
/* Abweichende Rechnungsadresse - Forumular - Popup */
function saveRubricselectionForm() {

	var el = document.forms['rubricselection'].elements['rubricid'];
	var val = getCheckedValue(el).toString();
		
	if(val == '')
		Ext.Msg.show({
			   title:'Fehler',
			   msg: 'Bitte w&auml;hlen Sie eine Rubrik aus.',
			   buttons: Ext.Msg.OK,			  
			   cls: 'msgbox'
			});		
	else {		
		document.getElementById('submitbutton').disabled = "disabled";
		loadRubricselectionForm(1,val);
	}
}

function uploadFile(type, id, classid) {
	
	if (windowG) {
		windowG.destroy();
	}

	switch(type){
		case 'file':
			lheadline = lfheadline;
			ltext = lftext;
			lbutton = lfbutton;
			linfosupload = linfosfileupload;
			break;
		case 'logo':
			lheadline = llheadline;
			ltext = lltext;
			lbutton = llbutton;
			linfosupload = linfoslogoupload
			break;
		case 'image':
			lheadline = liheadline;
			ltext = litext;
			lbutton = libutton;
			linfosupload = linfosimageupload;
			break;
		case 'video':
			lheadline = lvheadline;
			ltext = lvtext;
			lbutton = lvbutton;
			linfosupload = linfosvideoupload;
			break;
	}

	windowG = new Ext.Window({
		renderTo: Ext.getBody(),
		resizable:false,
		draggable: false,
		width: 480,
		cls: 'supportpopup fileupload',		
		minWidth: 300,
		minHeight: 200,
		bodyStyle:'',
		buttonAlign:'center',
		items: [{html:
			'	<div class="fileuploadbg">'+
			'		<div class="window_header">'+
			'			<a title="'+lclose+'" onclick="windowG.close(); return false;" href="#">'+lclose+'</a>'+
			'		</div>'+
			'		<h1>'+lheadline+'</h1>'+
			'		<p>'+ltext+'</p>'+
			'		<div class="form">'+
	        '   	 	<form action="/?event=cmp.cst.classifieds2.uploadfile&pk='+ classid +'&place='+ id +'&type='+ type +'" method="post" target="upload" enctype="multipart/form-data" onsubmit="lockUpload();return true;">'+
	        '				<div class="clearfix ">'+
            '					<input size="46" type="file" class="text" name="file" />'+	
            '				</div>'+
            '' 				+ linfosupload +
			'				<div id="uploadsubmitbutton" class="submitbutton">'+
			'					<input type="submit" class="submit" value="'+lbutton+'" id="submitbutton">'+
			'				</div>'+
			'			</form>'+
	        '		</div>'+
	        '		<div class="classifiedfooter clearfix">'+
	        '			<div class="buttonset">'+
	        '				<div class="submitbutton">'+
	        '					<input type="button" value="'+ lclose +'" class="submit upload" onclick="windowG.close(); return false;"/>'+
	        '				</div>'+
	        '			</div>'+
	        '		</div>'+
			'		<iframe style="display:none;" name="upload"></iframe>'+
			'	</div>'
		}],
		plain:false,
		floating:true,
		modal:true,
		closable: false,
		title:'',
		shadow:false
	});
	windowG.show(1);
}

function deleteFile(type, id, classid) {
	
	if(id == 3) 
		dmy = 'last';
	else
		dmy = '';
	
	switch(type){
		case 'file':
			document.getElementById(type + id).innerHTML = ''+
			''+
			'	<div class="item data '+ dmy +'">'+
			'		<div class="edit">'+
			'			<a href="javascript: uploadFile(\''+ type +'\', '+ id +', ' + classid + ');" class="upload">'+laddfile+'</a>'+
			'		</div>'+
			'		<div class="image">'+
			'			<img alt="'+ laddfile +'" src="/img/icons/up_pdf.gif" class="defaultimage"/>'+
			'			'+ linfosfile +''+
			'		</div>'+
			'		<div class="caption"></div>'+
			'	</div>'+
			'	<input type="hidden" name="file'+ id +'" value="" >'+
			'	<input type="hidden" name="filename'+ id +'" value="" >'+
			'';
			break;
		case 'image':
			document.getElementById(type + id).innerHTML = ''+
			''+
			'	<div class="item '+ dmy +'">'+
			'		<div class="edit">'+
			'			<a class="upload" href="javascript: uploadFile(\''+ type +'\', '+ id +', '+ classid +');">'+laddimage+'</a>'+
			'		</div>'+
			'		<div class="image">'+
			'			<img src="/img/icons/up_image.png" alt="'+ laddimage +'" class="defaultimage"/>'+
			'			'+ linfosimage +''+
			'		</div>'+
			'		<div class="caption"></div>'+
			'		<input type="hidden" name="image'+ id +'" value="" />'+
			'		<input type="hidden" name="imagepath'+ id +'" value="" />'+
			'		<input type="hidden" name="imagename'+ id +'" value="" />'+
			'	</div>'+
			'';
			break;
			
		case 'logo':
			document.getElementById(type + id).innerHTML = ''+
			''+
			'	<a href="javascript: uploadFile(\''+ type +'\', '+ id +', '+ classid +');" class="companylogo">'+laddlogo+'</a>'+
			'	'+ linfoslogo +
			'	<input type="hidden" name="companylogo" id="companylogo" value="">'+
			'	<input type="hidden" name="companylogoname"  value="">'+
			'	<input type="hidden" name="companylogopath" value="">'+
			'';
			break;
		case 'video':
			document.getElementById(type + id).innerHTML = ''+
			''+
			'	<div class="item '+ dmy +'">'+
			'		<div class="edit">'+
			'			<a class="upload" href="javascript: uploadFile(\''+ type +'\', '+ id +', '+ classid +');">'+laddvideo+'</a>'+
			'		</div>'+
			
			'		<input type="hidden" name="video'+ id +'" value="" />'+
			'		<input type="hidden" name="videopath'+ id +'" value="" />'+
			'		<input type="hidden" name="videoname'+ id +'" value="" />'+
			'		<input type="hidden" name="thumbnail'+ id +'" value="" />'+
			'		<input type="hidden" name="thumbnailpath'+ id +'" value="" />'+
			'		<input type="hidden" name="thumbnailname'+ id +'" value="" />'+
			'	</div>'+
			'';
			break;
	}
}

function lockUpload(){
	document.getElementById('uploadsubmitbutton').innerHTML = '<span>'+ luploadstarted +'</span><img src="/img/icons/progressbar.gif"/>';
}

function confirmMyClassifiedActions(title,msg,id,hashcode,type){
	var registerPositionStore;
	
	//Show a dialog using config options:
	Ext.Msg.show({
	   title: title,
	   msg: msg,
	   buttons: Ext.Msg.YESNO,
	   fn: function(btn){
		   if(btn == 'yes'){
			   registerPositionStore = new Ext.data.JsonStore({
					url: '/?event=cmp.cst.classifieds2.doreworkingactions&random=' + Math.random(),
					root: 'DATA',
					autoLoad: true,
					fields: ['FORM', 'SUCCESSFULLYSENT'],
					baseParams: {
						  id: id
						, type: type
						, hashcode: hashcode
					},
					listeners: {
						load: function(store, records) {
							for(var i=0;i<records.length; i++){	
								if(records[i].data.SUCCESSFULLYSENT.CODE){
									location.reload();
								}					
							}	
							windowG.center();
						}			
					}
				}); 
		   } else {}
	   },
	   animEl: 'elId',
	   cls: 'msgbox'
	});
}

function getBanknameByCode(bankcode) {
	var i = 0;
	if(!isNaN(bankcode) && bankcode > 0){
		registerPositionStore = new Ext.data.JsonStore({
			url: '/?event=cmp.cst.classifieds2.getbankidentification&bankcode='+bankcode,
			root: 'DATA',
			autoLoad: true,
			baseParams: {
				bankcode: bankcode
			},
			fields: ['PKCSTBANKIDENTIFICATIONS', 'BANKCODE', 'WEBTITLE', 'SHORTTITLE'],
			listeners: {
				load: function(store, records) {
					if(records[0] != undefined){
						document.getElementById('bankname').value = records[0].json[3];
						document.getElementById('accountnumber').focus();
					}else{
						document.getElementById('bankcode').focus();
					}
				}
			}
		});
	}
}

function updateDateEnd(idfrom,idto,i) {

	var d = [];
	if(document.getElementById(idfrom).value.toString().length != 0 && isDate(document.getElementById(idfrom).value.toString())){
		
		d = document.getElementById(idfrom).value.toString().split('.');
		if(d[2].length == 2){
			d[2] = '20'+d[2];
		}
		// javascript datemonths begins with 0
		d = new Date(d[2], d[1]-1, d[0]);
		d = DateAdd('d', d, i);
		
		try {
			d = d.format('d.m.Y');
			if(!d.match(/NaN/g))
				document.getElementById(idto).value = d;
			else
				document.getElementById(idto).value = '';
		} catch(err) {}
	}else{
		document.getElementById(idto).value = '';
	}
}

function validateDate(idfrom)
{
	var elVal = document.getElementById(idfrom).value.toString();
	var today = new Date();
	var todayVal = today.format("d.m.Y");
	
	if(elVal.length != 0){
		//dates (value of inputfield)
		if(isDate(elVal)){
			if(dateCompare(elVal,todayVal) == -1){
				elVal = '';
			}
			document.getElementById(idfrom).value = elVal;
		}else{
			elVal = '';
		}
	}
	document.getElementById(idfrom).value = elVal;
}

function isDate(value)
{
	var datePat = /^(\d{1,2})(.)(\d{1,2})(.)(\d{2,4})$/;
	var matchArray = value.match(datePat); // is the format ok?

	if (matchArray == null) {
		return false;
	}else{
		return true;
	}
}

function dateCompare(dateVal1,dateVal2)
{
	var dateValParts1 = dateVal1.split('.');
	if(dateValParts1[2].length == 2){
		dateValParts1[2] = '20'+dateValParts1[2];
	}
	var date1 = new Date(dateValParts1[2], dateValParts1[1]-1, dateValParts1[0]);
	
	var dateValParts2 = dateVal2.split('.');
	if(dateValParts2[2].length == 2){
		dateValParts2[2] = '20'+dateValParts2[2];
	}
	var date2 = new Date(dateValParts2[2], dateValParts2[1]-1, dateValParts2[0]);
	
	if(date1 == date2) {
    	// date1 is equal to date2
        return 0;
    } else if(date1 < date2) {
    	// date1 is earlier than date2
    	return -1;
    } else {
    	// date1 is later than date2
    	return 1;
    }
} 

function DateAdd(ItemType, DateToWorkOn, ValueToBeAdded)
{
    switch (ItemType) {
        //date portion        
        case 'd': //add days
            DateToWorkOn.setDate(DateToWorkOn.getDate() + ValueToBeAdded)
            break;
        case 'm': //add months
            DateToWorkOn.setMonth(DateToWorkOn.getMonth() + ValueToBeAdded)
            break;
        case 'y': //add years
            DateToWorkOn.setYear(DateToWorkOn.getFullYear() + ValueToBeAdded)
            break;
        //time portion        
        case 'h': //add days
            DateToWorkOn.setHours(DateToWorkOn.getHours() + ValueToBeAdded)
            break;
        case 'n': //add minutes
            DateToWorkOn.setMinutes(DateToWorkOn.getMinutes() + ValueToBeAdded)
            break;
        case 's': //add seconds
            DateToWorkOn.setSeconds(DateToWorkOn.getSeconds() + ValueToBeAdded)
            break;
    }
    return DateToWorkOn;
}

function prepareSubmit(formid) {
	
	if(formid == "formstep30"){
		var bankcode = 0;	
		var elBC = document.getElementById('bankcode');
		
		if(elBC){
			bankcode = elBC.value;			
			getBanknameByCode(bankcode);
		}	
		
		setTimeout("document.forms['" + formid + "'].submit();", 2000);		
	}
	
}


function setMandatoryOnStep30Layer() {
	// lastschriftverfahren
	var elcountry = document.getElementById('country_i');
	var valcountry = elcountry.options[elcountry.selectedIndex].value.toString();
	
	// 57 = Deutschland! Diese Box gibt es nur fuer Inlandskunden
	if(valcountry != '' && valcountry == 57){		
		document.getElementById('taxidentnumbermandatoryicon_i').innerHTML = "";
	}else{		
		document.getElementById('taxidentnumbermandatoryicon_i').innerHTML = "*";		
	}
}

function setBindsOnStep30Layer(){
	var elcountry = Ext.get('country_i');
		
	elcountry.on('change',setMandatoryOnStep30Layer,false);	
}
