var pathArray = window.location.pathname.split('/');
var locale = pathArray[2];



var basket_msg_1="La seguente pagina \u00E8 stata aggiunta al carrello di stampa:  \n- ";
var basket_msg_2="La pagina \u00E8 gi\u00E0 presente nel carrello:  \n- ";
var basket_msg_3="Ci dispiace, il carrello \u00E8 pieno. Per favore stampa e/o cancella dei record per liberare spazio";
var basket_msg_4="";
var basket_msg_5="Non ci sono pagine da stampare";

var basket_msg_1_EN="The following page has been added to the Print Basket:  \n- ";
var basket_msg_2_EN="This page is in your Print Basket yet:  \n- ";
var basket_msg_3_EN="Sorry, the Basket is full. Please print and/or delete entries from it";
var basket_msg_5_EN="There are no pages to print";

var printPage   ="/corporate/"+locale+"/site/printbasket/printpage.html";

var maxCookieLength = 2200;

function makePostAjaxRequest(url,params,callBack) {
	  http_request = false;
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
	    http_request = new XMLHttpRequest();
	    if (http_request.overrideMimeType) {
	      http_request.overrideMimeType('text/xml');
	      // See note below about this line
	    }
	  } else if (window.ActiveXObject) { // IE
	    try {
	      http_request = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	    try {
	      http_request = new ActiveXObject("Microsoft.XMLHTTP");
	      } catch (e) {}
	    }
	  }

	  if (!http_request) {
	    alert('Giving up :( Cannot create an XMLHTTP instance');
	    return false;
	  }
	  http_request.onreadystatechange = callBack;
	  http_request.open('POST', url, true);
	  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  http_request.setRequestHeader("Content-length", params.length);
	  http_request.setRequestHeader("Connection", "close");
	  
	  http_request.send(params);
	}




function addToPrint(title, URL, uuid) {
  var a_temp_title = title.split('@');
  printlist1=getCookie('print_basket_Pirelli')

  if ((window.printlist1 == null)||(window.printlist1 == '')) {
    var expDays = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
    expdate=exp.toGMTString();
    document.cookie='print_basket_Pirelli={'+a_temp_title[0]+'@'+URL+'@'+uuid+'}; path=/; expires ='+ expdate;
    if(locale=="it"){
    	alert(basket_msg_1 + title);
    }
	else{
		alert(basket_msg_1_EN + title);
	}
  } else {
	  
//	  results = printlist1.search('{'+a_temp_title[0]+'\|'+URL+'}');
    results = printlist1.search(uuid);
    if (results==-1) {
      addedid='{'+a_temp_title[0]+'@'+URL+'@'+uuid+'},' + printlist1
      if (addedid.length > maxCookieLength ) {
        if(locale=="it"){
        	alert(basket_msg_3);
        }
    	else{
    		alert(basket_msg_3_EN);
    	}
      } else {
        var expDays = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
        expdate=exp.toGMTString();
        document.cookie='print_basket_Pirelli=' + addedid + '; path=/; expires ='+ expdate;
        if(locale=="it"){
        	alert(basket_msg_1 + title);
        }
    	else{
    		alert(basket_msg_1_EN + title);
    	}
      }
    } else {
	    if(locale=="it"){
	    	alert(basket_msg_2 + title);
	      }
	  	else{
	  		alert(basket_msg_2_EN + title);
	  	}
    }
  }
}

function getCookie(name) {
	//alert("name: "+name);
	var dc = document.cookie;
	var prefix = name + '=';
	var begin = dc.indexOf('; ' + prefix);
  if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) {
			return null;
		}
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(';', begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}
	
function clearBasket() {
	var container = document.getElementById('results');
	container.innerHTML='';
}

function createBasket() {
	var container = document.getElementById('results');
	var noCookie = document.getElementById('PrintBasketNoCookie');
			
	var printlist1=getCookie('print_basket_Pirelli');
	if (!printlist1) {
		//non ci sono pagine nei cookie
		noCookie.style.display='';	
	} else {
		noCookie.style.display='none';
		var item_text = '';
		var item_link = '';
						  
		var printlist1_array = printlist1.split(',');
						  
		for (var loop=0; loop < printlist1_array.length; loop++) {
							  	
			item_t = printlist1_array[loop];
			temp_t = item_t.split('@');
			item_text = temp_t[0].substring(1, temp_t[0].length);
			//alert("item_text: "+item_text);
			if (!temp_t[1]) {
				continue;
			}
			item_link = temp_t[1].substring(0, temp_t[1].length-1);
			//alert("item_link: "+item_link);
					  	
			var element=document.createElement('div');
			element.setAttribute('class','riga_risultatiRicerca'); 
			element.setAttribute('className','riga_risultatiRicerca');
			element.setAttribute('id', 'record_' + loop);
						  	
			var title=document.createElement('div');
			title.setAttribute('class','sx');       
			title.setAttribute('className','sx');
			//title.innerHTML=item_text;
			var title_lnk=document.createElement('a');
			title_lnk.setAttribute('href', item_link);
			title_lnk.setAttribute('target', 'blank');
			title_lnk.innerHTML=item_text;
			title.appendChild(title_lnk);
						  	
			var delete_btn=document.createElement('div');
			delete_btn.setAttribute('class','dx img_risultatiRicerca');  
			delete_btn.setAttribute('className','dx img_risultatiRicerca');
			var delete_lnk=document.createElement('a');
			delete_lnk.setAttribute('href', 'javascript:removePrint(\"'+printlist1_array[loop]+'\")');
			var delete_img=document.createElement('img');
			delete_img.setAttribute('src','/docroot/corporate/common/gfx/ico/delete.png');
			delete_img.setAttribute('width','20');
			delete_img.setAttribute('height','22');  
			delete_img.setAttribute('alt','delete');
						  	
			delete_btn.appendChild(delete_lnk);
			delete_lnk.appendChild(delete_img);
						  	
			var print_btn=document.createElement('div');
			print_btn.setAttribute('class','dx img_risultatiRicerca'); 
			print_btn.setAttribute('className','dx img_risultatiRicerca');
			var print_lnk=document.createElement('a');
			print_lnk.setAttribute('href', 'javascript:printSingle(\''+loop+'\')');
			//print_lnk.setAttribute('target', 'blank');
			var print_img=document.createElement('img');
			print_img.setAttribute('src','/docroot/corporate/common/gfx/ico/print.png');
			print_img.setAttribute('width','20');
			print_img.setAttribute('height','22');  
			print_img.setAttribute('alt','print');
						  	
			print_btn.appendChild(print_lnk);
			print_lnk.appendChild(print_img);
						  	
			element.appendChild(title);
			element.appendChild(delete_btn);
			element.appendChild(print_btn);
		                        
			container.appendChild(element);
		}
	}
}

function refresh() {
	clearBasket();
	createBasket();
}

function removePrint(ID) {
	printlist1=getCookie('print_basket_Pirelli');
	var printlist1_array = printlist1.split(',');
	var printlist2='';
//	alert("pL1.length "+printlist1_array.length);
	if (printlist1_array.length==1) {
		    document.cookie = 'print_basket_Pirelli='+printlist2+'; path=/';
	} else {
		for (var loop=0; loop < printlist1_array.length; loop++) {
//alert(loop+";\n pL1Arr: "+printlist1_array[loop]+"\n pL2: "+printlist2);
			if (!(ID==printlist1_array[loop])) {
//				if (window.printlist2 != '') {
		    	if (printlist2 != '') {
					printlist2=printlist1_array[loop]+','+printlist2;
		        } else {
					printlist2=printlist1_array[loop];
		        }
			}
		}

//		alert("COOKIE_remove: "+printlist2);
		document.cookie='print_basket_Pirelli='+printlist2+'; path=/';
	}
	refresh();
}
function removeAll() {
	makeNull = '';
	document.cookie = 'print_basket_Pirelli='+makeNull+'; path=/'; 
	refresh();
}
function checkCookie(){
	var present=getCookie('print_basket_Pirelli');
	return present;
}

function printAll(){
	if (checkCookie()) {
		window.open(printPage + '?print=all', '_blank', 'width=640, height=420, toolbar=no, scrollbars=yes, status=0, menubar=yes, resizable=yes');
	} else {
		if(locale=="it"){
			alert(basket_msg_5);
	    }
		else{
			alert(basket_msg_5_EN);
		}
	}
}

function printSingle(pageIndex){
	if (checkCookie()) {
		window.open(printPage + '?print='+pageIndex, '_blank', 'width=640, height=420, toolbar=no, scrollbars=yes, status=0, menubar=yes, resizable=yes');
	} else {
		if(locale=="it"){
			alert(basket_msg_5);
	    }
		else{
			alert(basket_msg_5_EN);
		}
	}
}

function printNow(uuid){
//	alert("! "+uuid);
	window.open(printPage + '?print=-1&title=' + escape(window.document.title) + '&url=' + escape(window.location) + '&uuid='+escape(uuid), '_blank', 'width=640, height=420, toolbar=no, scrollbars=yes, status=0, menubar=yes, resizable=yes');
}


function saveNote(i){
	var textValue = trim(document.getElementById('note_text_area_' + i).value);

	$.ajax( {
		url : '/corporate/editcorporatenote.htm',
		data : {message: textValue, idNote: i},
		type : 'POST',
		success: function(){
			clearEditForm(i, textValue)
		},
		error : function(error) {
			clearEditForm(i, textValue)
			alert('note not saved!');
		}
	});

}

function clearEditForm(i, textValue){
	var text = document.getElementById('notes_text_' + i);
	var area = document.getElementById('notes_edit_text_' + i);
	text.innerHTML = textValue;
	text.style.display='block';
	area.style.display='none';
	var href_edit = document.getElementById('href_edit_' + i);
	var img_edit = document.getElementById('img_edit_' + i);
	href_edit.setAttribute('href', 'javascript:editNote("' + i + '")');
	img_edit.setAttribute('alt','edit');
	img_edit.setAttribute('src','/docroot/corporate/common/gfx/ico/edit.png');
	var note = document.getElementById('note_' + i);
	note.setAttribute('class','riga_risultatiRicerca');
	note.setAttribute('className','riga_risultatiRicerca');
}


function emptyCallback() {
	if (http_request.readyState == 4) {
		if (http_request.status != 200) {
			alert("out of synch");
			window.reload();
		}
	}
}
function trim(str){
	return str.replace(/^\s+|\s+$/g,"");
}

function refreshNotes(){
	var params = '';
	makePostAjaxRequest("/web/portal/notes/ListNote.do", params, repaintNote);
	
}

function deleteAllNotes() {
	$.ajax( {
		url : '/corporate/deleteallcorporatenote.htm',
		type : 'POST',
		success: function(){
			repaintNotes();
		},
		error : function(error) {
			alert('notes not deleted!');
		}
	});
}

function repaintNotes() {
	var container = document.getElementById('container');
	container.innerHTML='';
	var notes = http_request.responseXML.getElementsByTagName('note');
	if (notes != null && notes.length>0) {
		for(i = 0; i < notes.length; i++) {
			var note = notes.item(i);
			var position = note.getAttribute('id');

			if (note.children) { //Firefox
				var title = note.children[0].childNodes[0].nodeValue;
				var text = note.children[1].childNodes[0].nodeValue;
			}
			else { //IE
				var title = note.childNodes[0].childNodes[0].nodeValue;
				var text = note.childNodes[1].childNodes[0].nodeValue;
			}
			var element=document.createElement('div');
			element.setAttribute('class','riga_risultatiRicerca');
			element.setAttribute("className", "riga_risultatiRicerca");
			element.setAttribute('id', 'note_' + position);
				
			var note_title=document.createElement('div');
			note_title.setAttribute('class','note_title');
			note_title.setAttribute("className", "note_title");
			note_title.setAttribute('id','notes_title_' + position);
			note_title.innerHTML=title;

			var note_text=document.createElement('div');
			note_text.setAttribute('class','note_text');
			note_text.setAttribute("className", "note_text");
			note_text.setAttribute('id','notes_text_' + position);
			note_text.innerHTML=text;

			var note_edit_text=document.createElement('div');
			note_edit_text.setAttribute('class','note_edit_text');
			note_edit_text.setAttribute("className", "note_edit_text");
			note_edit_text.setAttribute('id','notes_edit_text_' + position);
			note_edit_text.setAttribute('style', 'display:none;');
			note_edit_text.style.display="none";
			var note_text_area = formFieldFactory('TEXTAREA','text');
			note_text_area.setAttribute('class', 'note_text_area');
			note_text_area.setAttribute("className", "note_text_area");
			note_text_area.setAttribute('id', 'note_text_area_' + position);
			note_text_area.setAttribute('cols', '60');
			note_text_area.setAttribute('rows', '2');
			note_text_area.innerHTML = text;
			
			note_edit_text.appendChild(note_text_area);
			
			var delete_btn=document.createElement('div');
			delete_btn.setAttribute('class','note_btn_dx');
			delete_btn.setAttribute("className", "note_btn_dx");
			var delete_lnk=document.createElement('a');
			delete_lnk.setAttribute('href', 'javascript:deleteNote(\"'+position+'\")');
			var delete_img=document.createElement('img');
			delete_img.setAttribute('src','/docroot/corporate/common/gfx/ico/delete.png');
			delete_img.setAttribute('width','20');
			delete_img.setAttribute('height','22');  
			delete_img.setAttribute('alt','delete');
						  	
			delete_btn.appendChild(delete_lnk);
			delete_lnk.appendChild(delete_img);

			var edit_btn=document.createElement('div');
			edit_btn.setAttribute('class','note_btn_dx');
			edit_btn.setAttribute("className", "note_btn_dx");
			var edit_lnk=document.createElement('a');
			edit_lnk.setAttribute('href', 'javascript:editNote(\"'+position+'\")');
			edit_lnk.setAttribute('id', 'href_edit_' + position);
			var edit_img=document.createElement('img');
			edit_img.setAttribute('src','/docroot/corporate/common/gfx/ico/edit.png');
			edit_img.setAttribute('width','20');
			edit_img.setAttribute('height','22');  
			edit_img.setAttribute('alt','edit');
			edit_img.setAttribute('id', 'img_edit_' + position);
						  	
			edit_btn.appendChild(edit_lnk);
			edit_lnk.appendChild(edit_img);

			var print_btn=document.createElement('div');
			print_btn.setAttribute('class','note_btn_dx');
			print_btn.setAttribute("className", "note_btn_dx");
			var print_lnk=document.createElement('a');
			print_lnk.setAttribute('href', '/web/portal/notes/PrintNote.do?position='+position);
			print_lnk.setAttribute('target', '_blank');
			
			var print_img=document.createElement('img');
			print_img.setAttribute('src','/docroot/corporate/common/gfx/ico/print.png');
			print_img.setAttribute('width','20');
			print_img.setAttribute('height','22');  
			print_img.setAttribute('alt','print');
						  	
			print_btn.appendChild(print_lnk);
			print_lnk.appendChild(print_img);


			element.appendChild(note_title);
			element.appendChild(note_text);
			element.appendChild(note_edit_text);
			element.appendChild(delete_btn);
			element.appendChild(edit_btn);
			element.appendChild(print_btn);

			container.appendChild(element);
			
		}
	}
}


function repaintNote() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			repaintNotes();
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function editNote(i){
	var text = document.getElementById('notes_text_' + i);
	var area = document.getElementById('notes_edit_text_' + i);
	text.style.display='none';
	area.style.display='block';
	var href_edit = document.getElementById('href_edit_' + i);
	var img_edit = document.getElementById('img_edit_' + i);
	href_edit.setAttribute('href', 'javascript:saveNote("' + i + '")');
	img_edit.setAttribute('alt','save');
	img_edit.setAttribute('src','/docroot/corporate/common/gfx/ico/save.png');
	var note = document.getElementById('note_' + i);
	note.setAttribute('class','riga_risultatiRicercaEditing');
	note.setAttribute('className','riga_risultatiRicercaEditing');
}

function deleteNote(i){
	$.ajax( {
		url : '/corporate/deletecorporatenote.htm',
		data : {idNote: i},
		type : 'POST',
		success : function() {
			var note = document.getElementById('note_' + i);
			note.parentNode.removeChild(note);
		},
		error : function(error) {
			alert('note not saved!');
		}
	});
	
}

function formFieldFactory(tag,nme,type){
	var el;

	try {
		el=document.createElement('<'+tag+(type?' type='+type:'')+' name='+nme+' >');
	} catch (e){
		el=document.createElement(tag);
		if (type) {
			el.type=type;
		}
	  	el.name=nme;
	}
	return el;
}

function addNote(){
	$.ajax( {
		url : '/corporate/corporatenote.htm',
		data : jQuery('#quickNotesForm').serialize(),
		type : 'POST',
		success : function() {
			$('#notes-tip').slideToggle('fast');
		},
		error : function(error) {
			alert('note not saved!');
		}
	});
}

