function Content_Shop_LoadArticleGrid(category) {
	var _sessionID = dojo.query("input[id$=tmpsessionId]")[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp"+_sessionID;
	var xhrArgs = {	
		url : _url,
		content: {	CONTEXT: "CONTENT", ACTION: "GETARTICLE", CATEGORY: category, FORCE: "1"},
		handleAs: 'xml',			
		load: function(response, ioArgs)  {Content_Shop_CreateArticleGrid (response, category)},
		error: function(response, ioArgs) {alert('Error getting Articledata.') }
	}
	dojo.xhrGet (xhrArgs);
}

function Content_Shop_PictureFormatter(value) {
	return('<img style="width:100px; height:100px" src=' + value + '></img>')
}

function Content_Shop_CreateOrderButton(value) {
	return('<button dojoType="dijit.form.Button" class="dijitReset dijitInline dijitButtonNode dijitButtonContents" style="width:100px;color:rgb(171,43,39);font-size:9pt" type="button" onClick=Content_Shop_AskForAdditionalArticleInfos("'+value+'")>Bestellen</button>')
}

function Content_Shop_AskForAdditionalArticleInfos(value) {
	var content = '<div style="width:220px; height:150px; border:1px solid lightgray; margin:5px;">';
	content += '<table style="width:100%; height:100% colspacing="5" cellspacing="5">'
	if (value.split("@@")[1] != "cat4") {
		content += '<tr><td><b>Bereich:</b></td><td><select style="width:100%" id="selectArticlePart"><option>Service</option><option>K\u00FCche</option><option>Hauswirtschaft</option></select></td></tr>';
	}
	content += '<tr><td><b>Anzahl:</b></td><td><input style="width:100%" id="inputArticleCount" type="text"></input></td></tr>';
	content += '<tr><td align="center" colspan="2"><button type="button" dojoType="dijit.form.Button" style="color:rgb(171,43,39);font-size:9pt" class="dijitReset dijitInline dijitButtonNode dijitButtonContents" onClick=Content_Shop_AddToShopBasket("'+value+'")>OK</button></td></tr>'
	content += '</table></div>';
	
	var shopAdditionalInfo = dijit.byId("shopArticleAdditionalInfo");
	if (shopAdditionalInfo != null) {
		shopAdditionalInfo.destroyRecursive();
	}
	shopAdditionalInfo = new dijit.Dialog({
												id: "shopArticleAdditionalInfo", 
												title: "Bestellzus\u00E4tze", 
												content: content,
												style: "border:1px solid rgb(192,192,192);border-radius: 5px;-webkit-border-radius: 5px;	-moz-border-radius: 5px;	-webkit-box-shadow: #666 1px 1px 1px;	-moz-box-shadow: #666 1px 1px 1px;	box-shadow: #666 1px 1px 1px;behavior: url(PIE.htc);"
											  });
	shopAdditionalInfo.show()
}


function Content_Shop_AddToShopBasket(value) {
	var _bereich = "Diverses"
	try {
		var options = dojo.byId("selectArticlePart").options;
		for (var i = 0; i< options.length; i++) {
			if (options[i].selected) {
				_bereich = options[i].value
			}
		}
		
	} catch(e) {
		;
	}
	var _anzahl = dojo.byId("inputArticleCount").value
	var _sessionID = dojo.query("input[id$=tmpsessionId]")[0].value;
	var _mySessionID = dojo.query("input[id$=mySession]")[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp"+_sessionID;
	
	if (_anzahl.search(/^[0-9]+$/) == -1) {
		alert("Die Eingabe f\u00FCr die Anzahl ist korrekt! Die Anzahl muss eine positive Zahl sein.");
		dojo.byId("inputArticleCount").focus()
		
	} else {
		dijit.byId("shopArticleAdditionalInfo").hide();
		var xhrArgs = {	
			url : _url,
			content: {CONTEXT: "CONTENT", ACTION: "ADDARTICLE", FORCE: "1", SESSIONID: _mySessionID, BEREICH: _bereich, ANZAHL: _anzahl, ARTICLEKEY: value.split("@@")[0], ARTICLECATEGORY: value.split("@@")[1]},
			handleAs: 'xml',			
			load: function(response, ioArgs)  {XSP.partialRefreshGet(dojo.query('div[id$="ShopBasket"]')[0].id);},
			error: function(response, ioArgs) {alert('Error getting Articledata.') }
		}
		dojo.xhrGet (xhrArgs);
	}
}

function Content_Shop_CreateArticleGrid(XML, category) {
	tmp = dijit.byId("LayoutShopLeftArticlesGrid");
	if (tmp != null) {
		tmp.destroy();
	}
	
	var itemArray = XML.getElementsByTagName('ENTRY');
	
	var header = 'font-size:8pt; font-weight:bold;';
	var cellCenter = 'font-size:8pt; text-align: center';
	var cell = 'font-size:8pt;';
	var viewLayout = {cells: [{	
							field		: 'Bild',
							name		: 'Bild',
							formatter	: Content_Shop_PictureFormatter,
							headerStyles: header,
							width		: '100px'},
							{field		: 'Artikel',
							name		: 'Artikelbezeichnung',	
							headerStyles: header,
							cellStyles	: cell,
							width		: '325px'},
							{field		: 'Preis',
							name		: '<center>Preis</center>',	
							headerStyles: header,
							cellStyles	: cellCenter,						
							width		: '50px'},
							{field		: 'Bestellen',
							name		: '<center>Bestellen</center>',	
							formatter	: Content_Shop_CreateOrderButton,
							headerStyles: header,
							width		: '105px'}
						]};
						
	var layout = [ viewLayout ];
 	var items = new Array ();
 	
 	for (var i = 0; i < itemArray.length; i++) { 	
				items.push ({		Key				: getXMLValue ( itemArray[i], 'UNID'),
									Bild			: getXMLValue ( itemArray[i], 'Bild'),
									Artikel			: getXMLValue ( itemArray[i], 'Artikel'),
									Semester		: getXMLValue ( itemArray[i], 'Semester'),
									Preis			: getXMLValue ( itemArray[i], 'Preis'),
									Bestellen		: getXMLValue ( itemArray[i], 'UNID')  + "@@" + category
							});		
	}

 	var dataStore = {	identifier	: 'Key',
 						label		: 'Titel', 
						items		: items
       	             };

	var data = new dojo.data.ItemFileReadStore({data: dataStore});
		
	var articleGrid = new dojox.grid.DataGrid({			id			: "LayoutShopLeftArticlesGrid",
														query		: { Key: '*' },
														store		: data,
														//autoHeight	: true,
														width: "100%",
														selectionMode: "none",
														structure	: layout},
														document.createElement('div'));

	// hier evtl noch fldContent_ProductOverviewBody ins XML schreiben lassen (ServerSide) und damit einen tooltip auf jeder Zeile erstellen
																            	
	dojo.byId("LayoutShopLeftArticles").appendChild(articleGrid.domNode);
	articleGrid.startup();	
}

function getXMLValue (_XMLRecord, _tag) {
	var _entry = _XMLRecord.getElementsByTagName(_tag);
	return getXMLValueData (_entry[0]);	
} 

function getXMLValueData (_entry) {
	if (_entry != undefined) {	
		if (document.all)  { 
			return _entry.text 
		} else { 
			return _entry.textContent 
		} 
	}
}


function Content_Shop_Basket_StartUp(id){
	var _sessionID = dojo.query('input[id$=WDFSessionID]')[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp"+_sessionID;
	var _data = dojo.query('input[id$=mySession]')[0].value;

	var xhrArgs = {
		url : _url,
		content: {	CONTEXT	: "CONTENT",					
					ACTION	: "GETSHOPBASKET",
					LANGUAGE: "G",
					DATA: _data,
					FORCE: "1"},
		handleAs: 'xml',
		load: function(response, ioArgs) {Content_Shop_Basket_Build(response, id)},
		error: function(response, ioArgs) {if (ioArgs.xhr.status > 0) { alert (response) }}
	}
	
	dojo.xhrGet (xhrArgs)		

	
}


function Content_Shop_Basket_Build (XMLData, id) {

	var _headerStyles = 'font-size:8pt; font-weight:bold';
	var _editableCellStyles = 'font-size:8pt; cursor: hand; cursor:pointer';
	var _cellStyles = 'font-size:8pt;';
	
	var tmp = dijit.byId('ArticleBasket');
	if (tmp != null) {
		tmp.destroy();
	}

	var _layout = [ {cells: [{	field: 'artikel',		name: 'Artikel',				headerStyles: _headerStyles, cellStyles: _cellStyles, width: '240px'},
	                        {	field: 'bereich',		name: 'Bereich',				headerStyles: _headerStyles, cellStyles: _cellStyles, width: '80px'},
							{	field: 'sprache',		name: 'Sprache',				headerStyles: _headerStyles, cellStyles: _cellStyles, width: '65px'},
							{	field: 'semester',		name: 'Semester',				headerStyles: _headerStyles, cellStyles: _cellStyles, width: '75px'},
							{	field: 'anzahl',		name: 'Anzahl',					headerStyles: _headerStyles, cellStyles: _editableCellStyles, width: '60px',editable:true},
							{	field: 'preis',			name: 'Preis',					headerStyles: _headerStyles, cellStyles: _cellStyles, width: '60px'},
							{	field: 'summe',			name: 'Summe',					headerStyles: _headerStyles, cellStyles: _cellStyles, width: '60px'},
							{	field: 'loeschen',		name: 'L\u00F6schen',	formatter: Content_Shop_CreateDeleteButton,	headerStyles: _headerStyles, cellStyles: _cellStyles, width: '75px'}]} ];
 	
 	var _itemlist = new Array ();
 	
 	dojo.forEach (XMLData.getElementsByTagName('ARTICLE'), function (_record, _idx) {
 		_itemlist.push ({key		: getXMLValue (_record, 'DELETE'),
 						 artikel	: getXMLValue (_record, 'NAME'),
 						 bereich	: getXMLValue (_record, 'BEREICH'),
 						 sprache	: getXMLValue (_record, 'SPRACHE'),
 						 semester	: getXMLValue (_record, 'SEMESTER'),
 						 anzahl		: getXMLValue (_record, 'ANZAHL'),
 						 preis		: getXMLValue (_record, 'PREIS'),
 						 summe		: getXMLValue (_record, 'SUMME'),
 						 loeschen	: getXMLValue (_record, 'DELETE')});
	});
	
	var _data = new dojo.data.ItemFileWriteStore({data: { identifier: 'key', label: 'titel', items: _itemlist }});
	
	

	var _grid = new dojox.grid.DataGrid({id			: 'ArticleBasket',
										query		: { key: '*' },
										canSort	: function() {return(false)},
										store		: _data,
										selectionMode: "none",
										singleClickEdit: true,
										structure	: _layout},
										document.createElement('div'));
	
	dojo.connect(_grid, "onApplyCellEdit", dojo.partial(onApplyCellEditHandler, _grid));	
	
	dojo.query("div[id="+id+"]")[1].appendChild(_grid.domNode);
	_grid.startup();
	if(_itemlist.length == 0){
		showInfoDialog("Information", "Es sind keine Artikel im Einkaufskorb vorhanden.<br/>Bitte f\u00FCgen Sie einen oder mehrere Artikel dem Einkaufskorb hinzu.<br><br><center><button type='button' dojoType='dijit.form.Button' class='dijitReset dijitInline dijitButtonNode dijitButtonContents' style='color:rgb(171,43,39);font-size:9pt' onclick=dijit.byId('infoDialogbasket').hide()>Schliessen</button></center>", false, "basket");
		dojo.query('*[id$=Bestellen]')[1].disabled=(_itemlist.length == 0)
	}
} // END: shopBasket_Build
	
function onApplyCellEditHandler(inGrid, inValue, inRowIndex, inFieldIndex) {	
	//get Session and AJAX.xsp
	var _sessionID = dojo.query('input[id$=mySession]')[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp";//+_sessionID;
	var _data = dojo.query('input[id$=myArticles]')[0].value;
	//alert(_sessionID);
	
	if (inValue.search(/^[0-9]+$/) == -1) {
		//String darf nur Zahlen 0-9 enthalten		
		alert("Die Eingabe f\u00FCr die Anzahl ist  nicht korrekt! Die Anzahl muss eine positive Zahl sein.");
		
	} else {
		var _wert = parseInt(inValue);
		
		var xhrArgs = {
				url : _url,
				content: {	CONTEXT	: "CONTENT",					
							ACTION	: "SHOPBASKETSAVE",
							LANGUAGE: "G",
							ITEM_ID: _data,
							ITEM_SESSION: _sessionID,
							WERT: _wert,
							ROW: inRowIndex,
							FORCE: "1"},
				handleAs: 'xml',
				load: function(response, ioArgs) {XSP.partialRefreshGet(dojo.query('div[id$="ShopBasket"]')[0].id)},
				error: function(response, ioArgs) {if (ioArgs.xhr.status > 0) { alert (response) }}
			}
			
		dojo.xhrGet (xhrArgs);
		
		var anz = inGrid.store.getValue(inGrid.getItem(inRowIndex), "anzahl");
		var preis = inGrid.store.getValue(inGrid.getItem(inRowIndex), "preis");
		
		inGrid.store.setValue(inGrid.getItem(inRowIndex), "summe", parseFloat(anz) * parseFloat(preis));
	}
}

function Content_Shop_CreateDeleteButton(value) {	
	return('<button dojoType="dijit.form.Button" type="button" onClick=Content_Shop_RemoveFromShopBasket("'+encodeURI(value)+'")>L\u00F6schen</button>')
}

function Content_Shop_RemoveFromShopBasket(delposition){
	
	//get Session and AJAX.xsp
	var _sessionID = dojo.query('input[id$=mySession]')[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp";//+_sessionID;

	
	var xhrArgs = {
			url : _url,
			content: {	CONTEXT	: "CONTENT",					
						ACTION	: "SHOPBASKETDELETEARTICLE",
						LANGUAGE: "G",
						ITEM_SESSION: _sessionID,
						ROW: delposition,
						FORCE: "1"},
			handleAs: 'xml',
			load: function(response, ioArgs) {XSP.partialRefreshGet(dojo.query('div[id$="ShopBasket"]')[0].id);Content_Shop_Basket_StartUp('shopBasket_GridContainer');},
			error: function(response, ioArgs) {if (ioArgs.xhr.status > 0) { alert (response) }}
		}
		
	dojo.xhrGet (xhrArgs);
	
}// END: Content_Shop_RemoveFromShopBasket



function Content_Shop_Order_Dialog() {
	XSP.partialRefreshGet(dojo.query('div[id$="divShopOrder"]')[0].id, {onComplete:function() {
		var shopAdditionalInfo = dijit.byId("shopAdditionalInfo");
		if (shopAdditionalInfo != null) {
			shopAdditionalInfo.destroyRecursive();
		}	
		var content = dojo.query('div[id$="shopOrderDialogContent"]')[0].innerHTML;
		
		shopAdditionalInfo = new dijit.Dialog({
													id: "shopAdditionalInfo", 
													title: "Bestellung abschicken", 
													content: content.replace('<input id="dynImpTermin">', '<input  type="date" name="date" datePattern= "dd.MM.yyyy" value="01.12.2011" dojoType="dijit.form.DateTextBox" id="inpTermin" style="width:140.0px" class="xspInputFieldEditBox"></input>').replace('<INPUT id=dynImpTermin>', '<input  type="date" name="date" datePattern= "dd.MM.yyyy" value="01.12.2011" dojoType="dijit.form.DateTextBox" id="inpTermin" style="width:140.0px"></input>') ,													
													//content: content.replace('<input id="dynImpTermin">', '<input id="inpTermin" value="01.12.2011" type="date" pattern="dd.MM.yyyy" id="dateTimeHelper2" dojoType="dijit.form.DateTextBox"></inputText>'),													
													style: "border:1px solid rgb(192,192,192);min-width: 930px; border-radius: 5px;-webkit-border-radius: 5px;	-moz-border-radius: 5px;	-webkit-box-shadow: #666 1px 1px 1px;	-moz-box-shadow: #666 1px 1px 1px;	box-shadow: #666 1px 1px 1px; behavior: url(PIE.htc);"
												  });
		shopAdditionalInfo.show();
		
	}});
}// END: Content_Shop_Order_Dialog



function Content_Shop_Save_Order() {
	
	var userSessionID = dojo.byId('mySession').value;
	var schule = dojo.query('input[id$=inpSchule]')[1].value;
	var name = dojo.query('input[id$=inpName]')[1].value;
	var vorname = dojo.query('input[id$=inpVorname]')[1].value;
	var strasse = dojo.query('input[id$=inpStrasse]')[1].value;
	var plz = dojo.query('input[id$=inpPLZ]')[1].value;
	var ort = dojo.query('input[id$=inpOrt]')[1].value;
	var land = dojo.query('select[id$=]')[1].value;
	var email = dojo.query('input[id$=inpEMail]')[1].value;
	var telefon = dojo.query('input[id$=inpTelefon]')[1].value;
	if (dijit.byId("inpTermin").isValid() && dijit.byId("inpTermin").valueNode.value.length > 0) {
		var termin = dijit.byId("inpTermin").valueNode.value;		
	} else {
		showInfoDialog("Fehlermeldung", "Bitte w\u00E4hlen Sie ein g\u00FCltiges Datum aus.", false, "termin");
		//dojo.byId("inpTermin").focus()
		return;
	}
	
	// Validierung der Felder
	if(validate("Schule",schule)){return;}
	if(validate("Name",name)){return;}
	if(validate("Vorname",vorname)){return;}
	if(validate("Strasse",strasse)){return;}
	if(validate("PLZ",plz)){return;}
	if(validate("Ort",ort)){return;}
	if(validateEmail("Email",email)){return;}
	
	
	var infoDialog = dijit.byId("orderInfoDialog");
	if (infoDialog != null) {
		infoDialog.destroyRecursive();
	}
	infoDialog = new dijit.Dialog({
		id: "orderInfoDialog",
		title: "Ihre Bestellung wurde \u00DCbermittelt!", 
		content: "Ihre Bestellung wurde an die WIGL \u00FCbermittelt. <br>Sie erhalten in k\u00FCrze eine e-Mail mit einer Bestellbest\u00E4tigung.<br><br><center><button type='button' dojoType='dijit.form.Button' class='dijitReset dijitInline dijitButtonNode dijitButtonContents' style='color:rgb(171,43,39);font-size:9pt' onClick=dijit.byId('orderInfoDialog').hide()>Schliessen</button></center>",
		style: "border:1px solid rgb(192,192,192); border-radius: 5px;-webkit-border-radius: 5px;	-moz-border-radius: 5px;	-webkit-box-shadow: #666 1px 1px 1px;	-moz-box-shadow: #666 1px 1px 1px;	box-shadow: #666 1px 1px 1px;behavior: url(PIE.htc);",
		onHide: function() {location.href = location.href}
	});							

	
	var _sessionID = dojo.query('input[id$=mySession]')[0].value;
	var _webPath = dojo.query('input[id$=WDFWebPath]')[0].value;
	var _url = _webPath+"/xpAJAX.xsp";
	
	var xhrArgs = {
			url : _url,
			content: {	CONTEXT	: "CONTENT",					
						ACTION	: "CREATESHOPORDER",
						FORCE: "1",
						USERSESSIONID: userSessionID,
						SCHULE: schule,
						NAME: name,
						VORNAME: vorname,
						STRASSE: strasse,
						PLZ: plz,
						ORT: ort,
						LAND: land,
						EMAIL: email,
						TELEFON: telefon,
						TERMIN: termin
						},
			handleAs: 'xml',
			load: function(response, ioArgs) {infoDialog.show()},
			error: function(response, ioArgs) {if (ioArgs.xhr.status > 0) { alert (response) }}
		}
		
	dojo.xhrGet (xhrArgs);

}

