function Wrapper() {
	this.i = 1;
	this.imagini = new Hash();
	this.droparea = null;
	this.containers = new Hash();
}

var wrapper = new Wrapper();

var cursor1 = new Element('div');
$(cursor1).id = 'cursor1';
$(cursor1).addClassName('imgCrop_handle imgCrop_handleNE');

var cursor2 = new Element('div');
$(cursor2).id = 'cursor2';
$(cursor2).addClassName('imgCrop_handle imgCrop_handleSE');

var cursor3 = new Element('div');
$(cursor3).id = 'cursor3';
$(cursor3).addClassName('imgCrop_handle imgCrop_handleSW');

var cursor4 = new Element('div');
$(cursor4).id = 'cursor4';
$(cursor4).addClassName('imgCrop_handle imgCrop_handleNW');
$(cursor4).setStyle({top:'-3px'});

function addDraggable(draggable,droparea){
	addDraggable(draggable,droparea, true, '', '', '', '','', '','');
}


function addDraggable(draggable,droparea, newElement, src, top, left, width, height, zIndex, containerRatio){
   
   if(droparea != null){
   		
   }else{
		droparea = $('shop_canvas');
   }
	
   wrapper.droparea = droparea;	


   if(draggable != null && draggable.id.indexOf('set') != -1){
		return loadSet(draggable.id.replace('draggable_set_', ''));
   }
	   
   var clone = createContainer();
   
   droparea.appendChild(clone);

   //make draggable
   makeDraggable2(clone, droparea);

   var image;
   var origHeight;	
   var origWidth;	

   //new element
 	if(newElement){
 		if(draggable != null){
    		var src = draggable.src;
	  		src = src.replace("_small.jpg", "_orig.png");
	  	}
	  	
	  	child(clone, '.pic').src = src;
		
		var left = Math.floor(Math.random()*410) + 'px';
		var top = Math.floor(Math.random()*410)+'px';
	
	  	clone.setStyle({top:top, left:left});
		
		image = getChild(clone, 'resizable_' + wrapper.i);
							
		if(image!= null && image.complete){
			//console.log('image complete');
			origHeight = parseInt(image.getStyle('height'));	
	   		origWidth = parseInt(image.getStyle('width'));
	   		setDefaultRes(clone, image, origHeight, origWidth);
			makeResizable(clone, droparea,image, origHeight, origWidth);
		}else if(image != null){
			//console.log('add observer');
			Event.observe($(image), 'load', function() {
				//console.log('image load triggered');
	  			origHeight = parseInt(image.getStyle('height'));	
		   		origWidth = parseInt(image.getStyle('width'));
		   		setDefaultRes(clone, image, origHeight, origWidth);
	  			makeResizable(clone, droparea,image, origHeight, origWidth)	
			});
		}

   }else{
   //load element
	if(left.indexOf('%') != -1){
			var dW = wrapper.droparea.getWidth();
			var dH = wrapper.droparea.getHeight();
			
			if(dW < dH){
				dH = dW * containerRatio;
			}else{
				dW = dH * containerRatio;
			}
			
			//console.log('dH: ' + dH + ' dW:' + dW);
        	left = parseInt(dW) * parseInt(left)/100 + 'px';
	        top = parseInt(top) * parseInt(dH)/100 + 'px';
			width = parseInt(width) * parseInt(dW)/ 100+ 'px';
        	height = parseInt(height) * parseInt(dH)/100+ 'px';
	}

	image = child(clone, '.pic');
	image.src = src;
	image.setStyle({top:top, left:left,width:width,height:height,zIndex:zIndex });
	clone.setStyle({top:top, left:left,width:width,height:height,zIndex:zIndex });
	
	
	if(image.complete){
			//console.log('image complete');
			origHeight = parseInt(image.getStyle('height'));	
	   		origWidth = parseInt(image.getStyle('width'));
			makeResizable(clone, droparea,image, origHeight, origWidth);
		}else{
			//console.log('add observer');
			Event.observe($(image), 'load', function() {
				//console.log('image load triggered');
	  			origHeight = parseInt(image.getStyle('height'));	
		   		origWidth = parseInt(image.getStyle('width'));
	  			makeResizable(clone, droparea,image, origHeight, origWidth)	
			});
		}
   }   
 	//return makeResizable(clone, droparea, origHeight, origWidth);
	return false;
}

function makeResizable(clone, droparea,image, origHeight, origWidth){
	//if(image.complete){
	
		//console.log('makeResizable image complete');
		//console.log('clone: '+ clone + ' droparea: ' + droparea + ' origHeight: ' + origHeight + ' origWidth: ' + origWidth);
	
	  //make resizable
	   var res = new Resizeable(clone, 
				{observers: [cursor1,cursor2,cursor3,cursor4],
				top: 6, 
				left: 6,
				bottom: 6,
				right: 6,
				keepRatio: 'width',
				onEndResize: function (event,direction){
		    		//stay in box
					var thisPos 	= clone.viewportOffset();
					var boxPos 	= droparea.viewportOffset();
					var diff_right 	= (thisPos.left + clone.getWidth()) - (boxPos.left + droparea.getWidth());
					var diff_bottom = (parseInt(clone.style.top) + clone.getHeight()) - (droparea.getHeight());
					var diff_left 	= boxPos.left - thisPos.left;
					var diff_top 	= boxPos.top - thisPos.top;
	
	  				var width = clone.getWidth() - diff_right -3;
					var height = clone.getHeight() - diff_bottom - 3;
					var left =  thisPos.left + diff_left - 3;
					var top = thisPos.top + diff_top;
	
					if(diff_right > 0){
						clone.style.width = width + "px";
						child(clone, '.pic').style.width = width + "px";
					}
			
					if(diff_bottom > 0){
						clone.style.height = height + "px";
						child(clone, '.pic').style.height = height + "px";
					}
		
					if(diff_left > 0){
						clone.style.left = left + "px";
						child(clone, '.pic').style.left = left + "px";
					}
				
					if(diff_top > 0){
						top = 0;
						clone.style.top = top + 'px';
						child(clone, '.pic').style.top = top + 'px';
						diff_bottom = parseInt((thisPos.top + clone.getHeight()) - (boxPos.top + droparea.getHeight()));
					}
	
					if(clone.getHeight() > droparea.getHeight()){
						clone.style.height = droparea.getHeight();
					}
	
					if(clone.getWidth() > droparea.getWidth()){
						clone.style.width = droparea.getWidth();
					}
									
					var image = child(clone, '.pic');
	
	   				var imgW = parseInt(clone.getStyle('width'));
					var imgH =  parseInt(clone.getStyle('height'));
					var style = image.style;
		 			style.width = imgW + 'px';
					style.height = imgH + 'px';
	
					// keep aspect ratio
					if(direction.indexOf('se') != -1){
						//ok
						var newWidth = imgW;
						var newHeight = getNewHeight(origHeight, origWidth,parseInt(imgW));
						diff_bottom = (parseInt(clone.style.top) + newHeight) - (droparea.getHeight());
						if(diff_bottom > 0 ){
							var height_diff = diff_bottom; 
							var width_diff  = getNewWidth(origHeight, origWidth,height_diff);
							newWidth = newWidth - width_diff;
							newHeight = getNewHeight(origHeight, origWidth, newWidth) - 3;
						}	
					}else if(direction.indexOf('e') != -1){
						var newWidth = getNewWidth(origHeight, origWidth, parseInt(imgH));
						var newHeight = imgH;
					
						diff_right = (clone.viewportOffset().left + newWidth) - (droparea.viewportOffset().left + droparea.getWidth());
	
						if(diff_right > 0){
							var width_diff = diff_right;
							var height_diff = getNewHeight(origHeight, origWidth,width_diff);
						
							newHeight = newHeight - height_diff;
							newWidth = getNewWidth(origHeight, origWidth, newHeight) - 3;
					
						}         
	   				}else{
					 //direction.indexOf('w') != -1
						var newWidth = imgW;
						var newHeight = getNewHeight(origHeight, origWidth,parseInt(imgW));
				
						diff_bottom = (parseInt(clone.style.top) + newHeight) - (droparea.getHeight());
					
					
						if(diff_bottom > 0 ){
							var height_diff = diff_bottom; 
							var width_diff  = getNewWidth(origHeight, origWidth,height_diff);
								
							newWidth = newWidth - width_diff;
							newHeight = getNewHeight(origHeight, origWidth, newWidth) - 3;
						}         
					
					}
							
					style.height = newHeight + 'px';
					style.width = newWidth + 'px';
					  
					var style = clone.style;
	
					style.height = newHeight + 'px';
					style.width = newWidth + 'px';
				}
				
			});
	
	   //add to hash
	  // wrapper.imagini.set(wrapper.i, getChild(clone, 'resizable_'+ wrapper.i));
	  // wrapper.containers.set(wrapper.i, getChild(droparea, 'container_'+ wrapper.i));
	  // wrapper.i++;	
		
	   //ascunde trage produsele aici		
	   if(wrapper.i != 0){
	   		$('empty').style.display='none';
	   }	
	   removeClasses('resizable_'+ (wrapper.i));
	   $(droparea).observe('mousedown', respondToClick);
	   $(clone).observe('mousedown', respondToClick);
   //}else{
   		//console.log('makeResizable image not complete');
   //}
   
   fixPNG(image);
   return false;
}

function setDefaultRes(container,image, origHeight, origWidth){
   //default resolution
   //console.log('defaultRes: image complete: ' +  image.complete + ' origHeight: ' + origHeight + ' origWidth: ' + origWidth);
   if (origHeight > origWidth){
	   	var defaultH = 200 + 'px';
	  	var defaultW =  parseInt(getNewWidth(parseInt(origHeight), parseInt(origWidth), parseInt(defaultH))) + 'px';
   }else{
	 	var defaultW = 200 + 'px';
		var defaultH =  parseInt(getNewHeight(parseInt(origHeight), parseInt(origWidth), parseInt(defaultW))) + 'px';
   }

   var style = container.style;			   
   style.width = defaultW;
   style.height = defaultH;
   
   style = image.style;	
   style.width =  defaultW;
   style.height = defaultH;

}

function respondToClick(event) {
	var id = event.element().id;

	if(id.indexOf('btn') != -1){
		return;
	}

	if(id.indexOf('resizable') != -1){
	   //s-a dat click pe imagine	
	     removeClasses(id);
	}else{
	   //s-a dat click pe shop_container
	   removeClasses(null);
	}        
}	
  
function addClasses(containerId){
	if($(containerId) != null){
		$(containerId).removeClassName('inactive');
	  	$(containerId).addClassName('imgCrop_selArea');
	    $(containerId).appendChild(cursor1);
	   	$(containerId).appendChild(cursor2);
		$(containerId).appendChild(cursor3);
		$(containerId).appendChild(cursor4);
	}
	
	//add toolbar
	$('toolbar').style.display='inline';
	$('toolbar').innerHTML = getToolbar();
	$('toolbar').observe('click', toolbar);
	
	//add publish buttons
	$('publish_t').style.display='inline';
	$('publish_t').innerHTML = getPublish();
	$('publish_t').observe('click', save);
	
}

function toolbar(event){
	if (event != null & event.element!= null)
	var id = event.element().id;
	if (id != null && id.indexOf('remove_btn') != -1){
		var el =$$('div.imgCrop_selArea').first();
	

		var keysImagini = wrapper.imagini.keys();
		var keysContainers = wrapper.containers.keys();
	        var elId = $(el).id;

	 	for (var x = 0; x<keysImagini.length;x++){
			var el1 = wrapper.containers.get(keysImagini[x]);

			var el2Id = $(el1).id;  
	
			if(elId.indexOf(el2Id) != -1){
				wrapper.imagini.unset(keysImagini[x]);	
				wrapper.containers.unset(keysContainers[x]);
				
			}
		}
		el.remove();
	}  

	//work
        
		
	if (id != null && id.indexOf('front_btn') != -1){
		var el =$$('div.imgCrop_selArea').first();
		el.style.zIndex = parseInt(el.style.zIndex) + 1;
	}  

	if (id != null && id.indexOf('back_btn') != -1){
		var el =$$('div.imgCrop_selArea').first();
		if(parseInt(el.style.zIndex) -1 >=0){
			el.style.zIndex = parseInt(el.style.zIndex) -1;
		}
	} 

	if (id != null && id.indexOf('clone_btn') != -1){
		var clone =$$('div.imgCrop_selArea').first();
		var img = child(clone, '.pic');

		addDraggable(null,null, false, img.src, parseInt(clone.style.top) + 20 + 'px',  parseInt(clone.style.left) + 20 + 'px',  clone.style.width,  clone.style.height, wrapper.i,parseInt(wrapper.droparea.getWidth())/parseInt(wrapper.droparea.getHeight()));
		
		clone = $('container_' + (wrapper.i - 1));
		//stay in box
		var diff_right 	= (clone.viewportOffset().left + clone.getWidth()) - (wrapper.droparea.viewportOffset().left + wrapper.droparea.getWidth());
		if(diff_right > 0){
			clone.style.left = (parseInt(clone.style.left) - diff_right) + 'px';
		}
		var diff_bottom = (parseInt(clone.style.top) + clone.getHeight()) - (wrapper.droparea.getHeight());
		
		if(diff_bottom > 0){
			clone.style.top = parseInt(clone.style.top) - diff_bottom + 'px';
		}

	} 

}


function removeClasses(skipId){
	
	for(i=1; i <= wrapper.i; i++){
		var element = $('container_' + i);
		if(skipId != null && skipId.indexOf('resizable') != -1){
			var nr = skipId.replace("resizable_", "");
			if(i == nr){
			   element = null;
			}		
	 	}
				
	       	if(element != null){
			if(getChild($(element),'cursor1') != null) $(element).removeChild(getChild($(element),'cursor1'));
			if(getChild($(element),'cursor2') != null) $(element).removeChild(getChild($(element),'cursor2'));
			if(getChild($(element),'cursor3') != null) $(element).removeChild(getChild($(element),'cursor3'));
			if(getChild($(element),'cursor4') != null) $(element).removeChild(getChild($(element),'cursor4'));
			$(element).removeClassName('imgCrop_selArea');	
			$(element).addClassName('inactive');
			
		}
	}
	
	//hide toolbar
	if($('toolbar') != null){
		$('toolbar').style.display='none';
	}

	if($('publish_t') != null && wrapper.imagini.keys().length <= 0){
		$('publish_t').style.display='none';
	}
	
	if (nr != null){
		addClasses('container_' + nr);
	}
}

function getId(){
	if($('container_' + wrapper.i) != null && $('container_' + wrapper.i) != 'undefined'){
		wrapper.i = wrapper.i + 1;
		getId();
	}else {
		return wrapper.i;
	}
	return wrapper.i;
}

clone: function createContainer() {

	var id = getId();

  	var div = new Element('div'); 
  	div.id = 'container_' + id;
    $(div).addClassName('imgCrop_selArea');
 
  	var newImage = new Element('img');
	newImage.id ='resizable_' + id;

	$(newImage).addClassName('pic');
   
  	$(div).appendChild(newImage);
   
	div.style.zIndex = id;

	$(div).appendChild(cursor1);
	$(div).appendChild(cursor2);
	$(div).appendChild(cursor3);
	$(div).appendChild(cursor4);


	wrapper.imagini.set(id,newImage);
	wrapper.containers.set(id, div);

  	return div; 
  	
}

function makeDraggable2(element, parent){

new Draggable(element,{revert:false,ghosting:false,starteffect:'',endeffect:'', snap: function(x,y,draggable) {
  function constrain(n, lower, upper) {
    if (n > upper) return upper;
    else if (n < lower) return lower;
    else return n-(n%10);
  }
  element_dimensions = Element.getDimensions(draggable.element);
  parent_dimensions = Element.getDimensions(parent);
  return[
    constrain(x, 0, parent_dimensions.width - element_dimensions.width),
    constrain(y, 0, parent_dimensions.height - element_dimensions.height)];
  }
});

}


function child(p, ch){
	var c = typeof p == 'string' ? byId(p).childNodes : p.childNodes;
	var type = ch.charAt(0);
	var ch = ch.slice(1, ch.length);
	for(i = 0; i < c.length; i++){
		if(type == '#'){
			if(c[i].id == ch) return c[i];
		}else if(type == '.'){
			if(c[i].className == ch) return c[i];
		}
	}
	return false;
}

function getChild(parent, childId){
var obj = null;
var children = $A(parent.childNodes);
children.each(function(child) {
 if(child.id == childId) obj = child; 	
});
 return obj;
}

function byId(id){ return document.getElementById(id); }

function getNewWidth(origHeight, origWidth, newHeight){
	return (origWidth * newHeight)/origHeight;
}

function getNewHeight(origHeight, origWidth, newWidth){
	return (newWidth * origHeight)/origWidth;
}


function getToolbar(){
return '<ul class="toolbar horizontal">'+
'<li>'+
'<button id="remove_btn" title="Sterge produs">'+
'Sterge produs'+
'</button>'+
'</li>'+
'</li>'+

'<li>'+
'<button id="front_btn" title="In fata">'+
'In fata'+
'</button>'+
'</li>'+
'</li>'+

'<li>'+
'<button id="back_btn" title="In spate">'+
'In spate'+
'</button>'+
'</li>'+
'</li>'+

'<li>'+
'<button id="clone_btn" title="Cloneaza">'+
'Cloneaza'+
'</button>'+
'</li>'+
'</li>'+

'</ul>';
	
}


function getVerticalToolbar(){
return '<ul class="toolbar vertical">'+
'<li>'+
'<button id="new_btn" title="Creaza set nou">'+
'Set nou'+
'</button>'+
'</li>'+
'</li>'+

'<li>'+
'<button id="publish_btn" title="Publica Setul">'+
'Publica'+
'</button>'+
'</li>'+
'</li>'+

'<li>'+
'<button id="save_btn" title="Salveaza Setul">'+
'Salveaza'+
'</button>'+
'</li>'+
'</li>'+

'</ul>';
	
}



function getPublish(){
var form = '<form id="publish" method="post" action="#"></form>'+ getVerticalToolbar();
return form;

}

function save(event){
if(event != null && event.element() != null){
	var id = event.element().id;
	if(id != null && id.indexOf('publish_btn') != -1){
		checkLogin('publish');
	}
	
	if(id != null && id.indexOf('save_btn') != -1){
		checkLogin('save');
	}

	if(id != null && id.indexOf('new_btn') != -1){
	//pagina noua
		newPage();
	}
}
}

function saveSet(){
		displayFeedback($('feedback_msg'),'Asteptati, se salveaza...',4);
		
		var keysImagini = wrapper.imagini.keys();
		var keysContainers = wrapper.containers.keys();
	
		var dW = 1;
		var dH = 1;
		
		var newSize = 0;
		
		var lWidth=wrapper.droparea.getWidth(); var rWidth=wrapper.droparea.getWidth(); var tHeight=wrapper.droparea.getHeight(); var bHeight = wrapper.droparea.getHeight();
	
		for (var x = 0; x<keysImagini.length;x++){
			var el2 = wrapper.containers.get(keysContainers[x]);
			var tmp = parseInt($(el2).style.top); 
			var tmp2 = parseInt($(el2).style.left);
			var tmp3 = wrapper.droparea.getHeight() - (parseInt($(el2).style.top)+parseInt($(el2).style.height));
			var tmp4 = wrapper.droparea.getWidth() - (parseInt($(el2).style.left) + parseInt($(el2).style.width));
			
			if(tmp < tHeight){
				tHeight = tmp;
			}
			
			if(tmp2< lWidth){
				lWidth = tmp2;
			}
			
			if(tmp3< bHeight){
				bHeight = tmp3;
			}
			
			if(tmp4< rWidth){
				rWidth = tmp4;
			}
		}

		maxWidth =  wrapper.droparea.getWidth() -(lWidth + rWidth);
		maxHeight =  wrapper.droparea.getHeight() - (tHeight + bHeight);
		
		if(maxHeight< maxWidth){
			newSize = maxWidth ;
		}else{
			newSize = maxHeight;
		}
		
		var containerRatio = dW/dH;

		for (var x = 0; x<keysImagini.length;x++){
			var el1 = wrapper.imagini.get(keysImagini[x]);
			var el2 = wrapper.containers.get(keysContainers[x]);

			var src = el1.src;
							
			var left = $(el2).style.left;
			if(parseInt(left)-lWidth==0)
				left = 0+'%';
			else
				left = ((parseInt(left)-lWidth))*100/parseInt(newSize)+'%';

			var top = $(el2).style.top;
			if(parseInt(top)-tHeight==0)
				top = 0+'%';
			else
				top = ((parseInt(top)-tHeight))*100/parseInt(newSize)+'%';

			var width = $(el2).style.width;
			
			width = (parseInt(width)*100)/parseInt(newSize)+ '%';
						
			var height = $(el2).style.height;
			height = (parseInt(height)*100)/parseInt(newSize)+'%';
			
			var ratio = parseInt($(el2).style.width) / parseInt($(el2).style.height);
			var zIndex = $(el2).style.zIndex;
			var idProd = src.replace('_orig.png', '');
			idProd  = idProd.substring(idProd.lastIndexOf('/') + 1, idProd.length);

			$('publish').appendChild(input('hidden', 'src_' + x, src));
			$('publish').appendChild(input('hidden', 'top_' + x, top));
			$('publish').appendChild(input('hidden', 'left_' + x, left));
			$('publish').appendChild(input('hidden', 'width_' + x, width));
			$('publish').appendChild(input('hidden', 'height_' + x, height));
			$('publish').appendChild(input('hidden', 'zIndex_' + x, zIndex));
			$('publish').appendChild(input('hidden', 'idProd_' + x, idProd));
			$('publish').appendChild(input('hidden', 'ratio_' + x, ratio));
				
			//console.log('top: ' + top + ' left: ' + left + ' width: ' + width + ' height:' + height);
 		}
			$('publish').appendChild(input('hidden', 'containerRatio', containerRatio));
			$('publish').appendChild(input('hidden', 'newSize', newSize));

		
		$('publish').appendChild(input('hidden', 'nr_imagini', ''+ keysImagini.length));
		
		var mesaj = 'Schita a fost salvata';	
		if($('titlu') != null && $('titlu').value.length > 0){
				mesaj = 'Setul a fost publicat';	
				$('publish').appendChild(input('hidden', 'titlu', ''+ $('titlu').value));	
				$('publish').appendChild(input('hidden', 'note', ''+ $('descriere').value));	
				$('publish').appendChild(input('hidden', 'tag_1', ''+ escape($('tag_1').value)));	
				$('publish').appendChild(input('hidden', 'tag_2', ''+ escape($('tag_2').value)));
				$('publish').appendChild(input('hidden', 'tag_3', ''+ escape($('tag_3').value)));
				$('publish').appendChild(input('hidden', 'tag_4', ''+ escape($('tag_4').value)));	
				$('publish').appendChild(input('hidden', 'tag_5', ''+ escape($('tag_5').value)));			
				$('publish').appendChild(input('hidden', 'categ', ''+ $('categorie').value));	
				$('publish').appendChild(input('hidden', 'idSetE', ''+ $('idSetE').value));
		}
		$('publish').action='save.html';
		$('publish').request({
			onSuccess:function(transport) {
						var resp = transport.responseText;
						if(resp.indexOf('OK') != -1){
							displayFeedback($('feedback_msg'),mesaj,4); 
							refreshTabs();
						} else{
							displayFeedback($('feedback_msg'),'A avut loc o eroare',4); 
						}
				}
			});
		$('publish').innerHTML="";

		return true;
}

function input(typ, nm, val )
{
	var elem = new Element('input');
	elem.type = typ;
	elem.name = nm;
	elem.value = val;
	return elem;
}

function loadSet(setId){
	newPage();
	var id= 'load';
	var url = '/load.html';
	new Ajax.Updater(id, url,{parameters: {id: setId}, asynchronous:true, evalScripts:true }); 
	return false;
}

function newPage(){

	//hide toolbar
	if($('toolbar') != null){
		$('toolbar').style.display='none';
	}

	var keysImagini = wrapper.imagini.keys();
	var keysContainers = wrapper.containers.keys();
	
	for (var x = 0; x<keysImagini.length;x++){

			var el1 = wrapper.imagini.get(keysImagini[x]);
			var el2 = wrapper.containers.get(keysContainers[x]);
		
			
			if(el1 != null){
				var id = el1.id; 
				$(id).remove();
				
			}

			if(el2 != null){
				$(el2).remove();
			}
	}
	
	wrapper.containers = new Hash();
	wrapper.imagini =  new Hash(); 
	wrapper.i = 1;
}

function checkLogin(functionCall){
	var loginOK = false; 
	
	var showLogin = false;
	new Ajax.Request("/check_login.html", 
				{
					asynchronous:false, 
					method:'GET',
					onSuccess:function(transport) {
						var resp = transport.responseText;
						if(resp.indexOf('username') != -1){
							loginOK = true;
							showLogin = false;
						}else{
							showLogin =  true;
							loginOK = false;
						}
					},
					contentType:'application/x-www-form-urlencoded' 
	}); 

	if(showLogin){
		var dialog = Dialog.confirm($('login').innerHTML, 
		{ 
			className:"alphacube", width:500, 
			okLabel: "Autentifica", cancelLabel: "Inchide",
			onOk:function(win){
			
				if($('user').value == '' || $('parola').value == '') { 
					$('login_error_msg').innerHTML='Introduceti numele de utilizator si parola'; 
					$('login_error_msg').show(); 
				}else{
				 	new Ajax.Request("/login.html?username="+$('user').value+"&password="+$('parola').value, 
					{
						asynchronous:false, 
						method:'POST',
						onSuccess:function(transport) {
							var resp = transport.responseText;
							if(resp.indexOf('Bine ai venit') != -1){
								loginOK = true;
								//refresh
								refreshLogin();
								if(functionCall != null && functionCall.length > 0){
									if(functionCall.indexOf('publish')!= -1){
										publishSet();	
									}else if(functionCall.indexOf('save')!= -1){
										saveSet();
									}else if(functionCall.indexOf('tabs')!= -1){
										refreshTabs();
									}else if(functionCall.indexOf('salveaza_produs')!= -1){
										//console.log('load panel: ' + functionCall);
										loadPanel(functionCall,'tab1');
									}else if(functionCall.indexOf('postComment')!= -1){
										postComment();
									}
								}
								return true;
							}else{
								$('login_error_msg').innerHTML='Nume utilizator sau parola incorecta!'; 
								$('login_error_msg').show(); 
							}
						},
						contentType:'application/x-www-form-urlencoded' 
					}); 
				}
				
				if(loginOK){
					return true;
				}else{
					Windows.focusedWindow.updateHeight(); 
					new Effect.Shake(Windows.focusedWindow.getId()); 
					return false;
				}
			}
		}); 
		dialog.setZIndex(1000);
	}else{
		if(functionCall != null && functionCall.length > 0){
			if(functionCall.indexOf('publish')!= -1){
				publishSet();	
			}else if(functionCall.indexOf('save')!= -1){
				saveSet();
			}else if(functionCall.indexOf('tabs')!= -1){
				refreshTabs();
			}else if(functionCall.indexOf('salveaza_produs')!= -1){
				loadPanel(functionCall,'tab1');
			}else if(functionCall.indexOf('postComment')!= -1){
				postComment();
			}
		}
	
	}
}

function refreshLogin(){
	new Ajax.Request("/getHtml.html?id=loginBar", 
	{
		asynchronous:false, 
		method:'GET',
		onSuccess:function(transport) {
			var resp = transport.responseText;
			$('loginBar').innerHTML = resp;
		},
		contentType:'text/html; charset=UTF-8'
	}); 
	return true;
}

function publishSet(){
	var dialog  = Dialog.confirm($('publishSet').innerHTML, 
		{ 
			className:"alphacube", width:500, 
			okLabel: "Publica", cancelLabel: "Inchide",
			onOk:function(win){
			var loginOK = false; 
				if($('titlu').value == '' || $('descriere').value == ''|| $('categorie').value == '0' || ($('tag_1').value=='' && $('tag_2').value=='' && $('tag_3').value=='' && $('tag_4').value=='' && $('tag_5').value=='')) { 
					$('publish_error_msg').innerHTML='Va rugam completati toate campurile'; 
					$('publish_error_msg').show(); 
					Windows.focusedWindow.updateHeight(); 
					new Effect.Shake(Windows.focusedWindow.getId()); 
					return false;
				}else{
					saveSet();
					return true;
				}
			}
	}); 
	dialog.setZIndex(1000);
}

function refreshTabs(){
	var activeTab = $$('a.active-tab').first().readAttribute('onclick');
	var idx = activeTab.indexOf('tab=');
	var tab;
	if(idx != -1){
		activeTab = activeTab.substring(idx + 4, idx + 5);
		if(parseInt(activeTab) > 0){
			loadPanel('/user_zone?tab=' + activeTab,'tab1');
		}
	}
}

function displayFeedback(element, message, timeout){
	var li = new Element('li');
	li.innerHTML = message;
	$(element).innerHTML = li.innerHTML;
	$(element).style.display='block';
	Element.hide.delay(timeout, $(element));
}	

var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage){	
    if ((version >= 5.5) && (version < 7) && (document.body.filters)){ 	
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
	   var imgTitle = (myImage.title) ?"title='" + myImage.title  + "' " : "title='" + myImage.alt + "' ";
	   var imgStyle = "display:inline-block;" + myImage.style.cssText;
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
	   myImage.outerHTML = strNewHTML;
   }
}

function createPublishForEdit(idSetE){
	new Ajax.Request("/editSetForm.html?idSetE="+idSetE, 
	{
		asynchronous:false, 
		method:'GET',
		onSuccess:function(transport) {
			var resp = transport.responseText;
			$('publishSet').innerHTML = resp;
		},
		contentType:'text/html; charset=UTF-8'
	}); 
	return true;
}