var win=null;
var urlPrefix = '';

function openPopup(myname,mypage,w,h,scroll,pos){
	if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
		else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
	settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win=window.open(mypage,myname,settings);
	win.focus();
}
function move(obj,step){
	// used to order combo items 
	d=document.getElementById(obj);
	min=0;
	max=d.options.length-1;
	current=d.selectedIndex;
	if ((current+step>=0)&&(current+step<=max))
	{
		var tmp_value=d.options[current].value;
		var tmp_text=d.options[current].text;
		d.options[current].value=d.options[current+step].value;
		d.options[current].text=d.options[current+step].text;
		d.options[current+step].value=tmp_value;
		d.options[current+step].text=tmp_text;
		d.selectedIndex=current+step;
	}		
}
function moveComboItem(objFrom,wFrom,objTo,wTo) {
	// from combo a to combo b
	if (!wFrom)	{
		var oFrom = document.getElementById(objFrom);
	} else {
		var oFrom = window.opener.document.getElementById(objFrom);
	}
	if (!wTo)	{
		var oTo = document.getElementById(objTo);
		var objChild = document;
	} else {
		var oTo = window.opener.document.getElementById(objTo);
		var objChild = window.opener.document;
	}	

	for (var j=0;j<oFrom.options.length;j++ )	{
		if (oFrom.options[j].selected){
			customAddComboItem(objChild,oTo,oFrom.options[j].value,oFrom.options[j].text,0);
			/*
			var newOpt = objChild.createElement("option");
			newOpt.setAttribute("value",oFrom.options[j].value);
			var texto = objChild.createTextNode(oFrom.options[j].text);
			newOpt.appendChild(texto);

			newOpt.text = oFrom.options[j].text;
			newOpt.value = oFrom.options[j].value;
			var sw = true;
			for (var i=0;i<oTo.options.length;i++ ){
				if (oTo.options[i].value == newOpt.value) {
					sw = false;
					break;
				}
			}
			if (sw)	{
				oTo.appendChild(newOpt);
			}
			*/
		}
	}
}
function customAddComboItem(objChild,obj,id,value,selected) {
			var newOpt = objChild.createElement("option");
			newOpt.setAttribute("value",id);

			if (selected) newOpt.setAttribute("selected",'selected');
			var texto = objChild.createTextNode(value);
			newOpt.appendChild(texto);

			newOpt.text = value;
			newOpt.value = id;
			var sw = true;
			for (var i=0;i<obj.options.length;i++ ){
				if (obj.options[i].value == newOpt.value) {
					sw = false;
					break;
				}
			}
			if (sw)	{
				obj.appendChild(newOpt);
			}
}

function select_all(obj,wObj){
	if (!wObj)	{
		d=document.getElementById(obj);
	} else d=window.opener.document.getElementById(obj);
	for (i=0;i<d.options.length;i++) {
		d.options[i].selected=true;
	}
}

function delComboItem(objName,wObj){
	if (!wObj)	{
		var obj = document.getElementById(objName);
	} else var obj = window.opener.document.getElementById(objName);
	for (var i=0;i<obj.options.length;i++ )	{
		if (obj.options[i].selected){
			obj.options[i]=null;
			i--;
		}
	}
}


function emptyElement(obj){
	var obj = document.getElementById(obj);
	switch (obj.type){
		case 'input':
		case 'hidden':
			obj.value='';
			break;
		default:
			if (obj.innerHTML){
				obj.innerHTML = '';
			}
	}
}

function printArea(prefixUrl){
	openPopup('Print',prefixUrl+'/includes/print.html',600,600,1,'center')
	//window.open(prefixUrl+'/includes/print.html','Print',"width=600,height=600,scrollbars=1");
}


function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function filterKeyPressNumeric(e) {
   var KeyID = (window.event) ? event.keyCode : e.keyCode;
}


function getAttrCombo(id_atr,combo_name,htmlObj,defValue,showNextObj,onchangeFunc) {
	$.ajax({
	   type: "GET",
	   async: false,
	   url: urlPrefix+"/index.php?module=ajax&op=getAttrCombo&combo_name="+combo_name+'&id_atr='+id_atr+'&item='+defValue+'&showNextObj'+showNextObj+'&onchange='+onchangeFunc,
	   success: function(msg){
		 $('#'+htmlObj).html(msg);
	   }
	 });		
}
function addOptionValue(htmlObj,arr) {
	 var arr = msg.split('**');
	 for (i=0;i<arr.length;i++){
//		 alert(arr[i]);
		vals = arr[i].split("##");
		var thisOpt   = document.createElement('option');
		thisOpt.value = val[0];
		thisOpt.appendChild(document.createTextNode(val[1]));
//		alert(thisOpt);
		$("#"+htmlObj).append(thisOpt);
	 }
}
/*
function getAttrComboOptions(htmlObj,id_atr,defValue,parentId) {
	ajaxManager.add({ 
		  type: "GET",
		  url: "/index.php?section=ajax&op=getAttrComboOptions&htmlObj="+htmlObj+"&id_atr="+id_atr+'&item='+defValue+'&parentId='+parentId,
		   success: function(msg){
//			  addOptionValue(htmlObj,arr);
			 var arr = msg.split('**');
			 selectedVal = new Array();
			 selectedVal[id_atr] = 0;
			 $('#loading_'+htmlObj).html("<img src='images/js_effects/loading.gif' width=15>");
			 document.getElementById(htmlObj).length=0;
			 for (i=0;i<arr.length;i++){
				val = arr[i].split("##");
		//		alert(vals);
		//		document.getElementById(htmlObj).options[document.getElementById(htmlObj).length] =	new Option(unescape(val[1]), val[0], false, val[2]);

				var thisOpt   = document.createElement('option');
				thisOpt.value = val[0];
				if (val[2]>0){
					selectedVal[id_atr] = val[0];
				}
				thisOpt.text = unescape(val[1]);
				document.getElementById(htmlObj).options[document.getElementById(htmlObj).length] = thisOpt;
			 }
			 $("#"+htmlObj).val(selectedVal[id_atr]);
			 $('#loading_'+htmlObj).html("");
		   }
	});
}
*/
function getAttrComboOptions(htmlObj,id_atr,defValue,parentId,firstElement) {	
    $('#loading_'+htmlObj).html("<img src='/images/js_effects/loading.gif' width=15>");
	ajaxManager.add({ 
		  type: "GET",
		  url: urlPrefix+"/index.php?module=ajax&op=getAttrComboOptions&htmlObj="+htmlObj+"&id_atr="+id_atr+'&item='+defValue+'&parentId='+parentId+'&firstElement='+firstElement,
		   success: function(msg){
			 $("#"+htmlObj).html(msg);
			 $('#loading_'+htmlObj).html("");
		   }
	});
}
/*
function getAttrHtml(htmlContainer,htmlObj,id_atr,defValue,parentId) {
	selectedItems = '';
	if (defValue==undefined) {
		defValue='';
	}
	if (defValue.constructor == Array) {
		for (i in defValue) {
			selectedItems += "&item[]="+defValue[i];
		}
	} else selectedItems = '&item='+defValue;

	 $("#"+htmlContainer).html("<img src='images/js_effects/loading.gif' width=15>");
	if (parentId==undefined) {
		parentId='';
	}
	ajaxManager.add({ 
		  type: "GET",
		  url: urlPrefix+"/index.php?section=ajax&op=getAttrHtml&formType="+formType+"&htmlContainer="+htmlContainer+"&htmlObj="+htmlObj+"&id_atr="+id_atr+'&additionalJs=refreshDependent'+selectedItems+'&parentId='+parentId,
		   success: function(msg){
			 $("#"+htmlContainer).html(msg);
		   }
	});
}

function refreshDependentAttr(id,isInit) {
	if (isInit) vals = attrInit[id]['value'];
		else {
			vals = $("#attr_"+id).val();
		}
	childs = new Array();
	if (typeof(attrInit[id])!='undefined' && typeof(attrInit[id]['childs'])!='undefined' && attrInit[id]['childs'].length) {
		for (var i=0;i<attrInit[id]['childs'].length;i++) {
			childId = attrInit[id]['childs'][i];
			if (isInit && childId && typeof(attrInit[childId]['value'])!='undefined') defVals = attrInit[childId]['value'];
				else defVals = '';
			getAttrHtml('divHtml_attr_'+childId,'attr_'+childId,childId,defVals,vals);
			if (typeof(attrInit[childId])!='undefined') refreshDependentAttr(childId,isInit);
		}
	}
}
*/
function getAttrHtml(htmlContainer,htmlObj,id_atr,defValue,parentId,isSearch,property,customHtml) {
	var selectedItems = '';
	if (defValue==undefined) {
		defValue='';
	}
//	if (defValue.constructor == Array) {
	if (typeof(defValue) == 'object') {
		var q=0;
		for (q in defValue) {
			selectedItems += "&item[]="+defValue[q];
		}
	} else selectedItems = '&item='+defValue;

	 $("#"+htmlContainer).html("<img src='/images/js_effects/loading.gif' width=15>");
	if (parentId==undefined) {
		parentId='';
	}
//	alert(id_atr + ' def: ' + defValue+ ' parent:'+parentId);
	ajaxManager.add({ 
		  type: "GET",
		  async: false,
		  url: urlPrefix+"/index.php?module=ajax&op=getAttrHtml&formType="+formType+"&htmlContainer="+htmlContainer+"&htmlObj="+htmlObj+"&id_atr="+id_atr+'&additionalJs=refreshDependent'+selectedItems+'&parentId='+parentId+(typeof('isSearch')!='undefined' && isSearch ? "&isSearch="+isSearch:"")+(typeof('property')!='undefined' && property ? "&property="+property:"")+(typeof('customHtml')!='undefined' && customHtml ? "&customHtml="+customHtml:""),
		   success: function(msg){
//			  alert(id_atr+' '+msg);
			 var jsReg=new RegExp("<script[^>]*>([^>]*)<\/script>", "gim");
			 var jsReg2=new RegExp("<\/*script[^>]*>", "gim");

			 var a = msg.match(jsReg);
			 msg = msg.replace(jsReg,'');

			 $("#"+htmlContainer).html(msg);
			 if (typeof(a)!="undefined" && a && a.length) {
				 var oScr = document.createElement('script');
				 oScr.type = 'text/javascript';
				 oScr.text='';
				 for (var i=0;i<a.length;i++) {
					oScr.text +="\r\n"+ a[i].replace(jsReg2,"");
				 }
	//			 alert(oScr.text);
				document.body.appendChild(oScr);
			 }

		   }
	});
}

function refreshDependentAttr(id,isInit,isSearch,property) {
	if (isInit) {
		var vals = attrInit[id]['value'];
	} else {
			var vals = $("#attr_"+id).val();
		}

	if (typeof(attrInit[id])!='undefined' && typeof(attrInit[id]['childs'])!='undefined' && attrInit[id]['childs'].length) {
		var i=0;
		for (i=0;i<attrInit[id]['childs'].length;i++) {
			var childId = attrInit[id]['childs'][i];
			var defVals = '';
			
			if (isInit && childId && typeof(attrInit[childId])!='undefined' && typeof(attrInit[childId]['value'])!='undefined') {
				defVals = attrInit[childId]['value'];
			}
			var childHtml = '';
			if (typeof(attrInit[childId])!='undefined') {
				childHtml = attrInit[childId]['html'];
			}
			if (childHtml=='mpopup' || childHtml=='popup' ) {
//				alert(id+ ' = '+attrInit[childId]+' '+childHtml);
				continue;
			}

			getAttrHtml('divHtml_attr_'+childId,'attr_'+childId,childId,defVals,vals,isSearch,property,childHtml);

			var has_property = -1;
			var tmp_id = childId;

			if (tmp_id==25) {
				has_property = $("#attr_3 option:selected").attr('has_sector');
			}
			if (tmp_id==26) {
				has_property = $("#attr_3 option:selected").attr('has_zone');
			}
			if (tmp_id==27) {
				has_property = $("#attr_3 option:selected").attr('has_subzone');
			}
			if (isNaN(has_property)) has_property = 0;
			has_property = parseInt(has_property);

			if (has_property != -1 && (typeof(isSearch) == 'undefined' || !isSearch )) {
					refreshDep = false;
					if (!has_property) {
						$('#attr_'+childId).val('');
						if (typeof(initRequired['attr_'+tmp_id]) == 'undefined') {
							 if (typeof(form_fields_conf)!='undefined') {
								 initRequired['attr_'+tmp_id] = form_fields_conf['attr_'+tmp_id]['required'];
							 } else initRequired['attr_'+tmp_id]=0;
						}
						form_fields_conf['attr_'+tmp_id]['required'] = 0;
						$('#tr_attr_'+tmp_id).hide();						
					} else {
						if (typeof(initRequired['attr_'+tmp_id]) != 'undefined') {
							 form_fields_conf['attr_'+tmp_id]['required'] = initRequired['attr_'+tmp_id];
						}
						$('#tr_attr_'+tmp_id).show();						
					}
					requiredStatus();
			}
			
			if (typeof(attrInit[childId])!='undefined' && typeof(attrInit[childId]['childs'])!='undefined' && attrInit[childId]['childs'].length) {
				refreshDependentAttr(childId,isInit,isSearch,property);
			}
		}
	}
}

function fillHtmlTags(obj,type,selectedId,skipFirst) {
	selObj = document.getElementById(obj);
	if (skipFirst)	{
		selObj.options.length = 1;
	} else selObj.options.length = 0;
	for (i in htmlTypes) {
		sw = false;
		switch (type) {
			case 'predefined':
				sw = htmlTypes[i]['isPredefined']; 
				break;
			case 'custom':
				sw = !htmlTypes[i]['isPredefined']; 
				break;
		}
//		alert(sw+' '+type+' '+htmlTypes[i]['name']);
		if (sw) {
			id = htmlTypes[i]['id'];
			value = htmlTypes[i]['name'];
			selected = htmlTypes[i]['id'] == selectedId ? 1:0;
			customAddComboItem(document,selObj,id,value,selected);
		}

	}
}

function addAttrValName(varName,type,attrId, attrValId, attrValName) {
	//type - single => varname, 
	//	multiple => varname[]
	var html = '';
	var strVarName = '';
	switch (type)	{
		case 'single':
//			alert("#div_attr_ids_"+attrId);
			var strVarName = varName;
			var strVarId = varName;
			if (typeof(self.parent)!='undefined') {
				self.parent.$('#div_attr_ids_'+attrId).html("");
			} else $('#div_attr_ids_'+attrId).html("");
			break;
		case 'multiple':
			var strVarName = varName+'[]';
			var strVarId = varName+'_'+attrValId;					
			if (typeof(self.parent)!='undefined') {
				self.parent.$('#div_attr_ids_'+attrId+'_'+attrValId).remove();
			} else $('#div_attr_ids_'+attrId+'_'+attrValId).remove();
			break;
	
	}

	html += '<div id="div_attr_ids_'+attrId+'_'+attrValId+'">';
	html += '<input type="hidden" name="'+strVarName+'" id="'+strVarId+'" value="'+attrValId+'">';
//	html += '<input type="button" value="-" onclick="if (confirm(\'Esti sigur ca vrei sa stergi?\')) $(\'#div_attr_ids_'+attrId+'_'+attrValId+'\').remove();">&nbsp;'+unescape(attrValName);
	html += "<table width='100%' cellspacing=0 cellpadding=0 border=0 class='itemTable'><tr><td>"+unescape(attrValName)+"</td><td width='50'><a href='javascript: void(0)' onclick=\"if (confirm('Esti sigur ca vrei sa stergi?')) $('#div_attr_ids_"+attrId+'_'+attrValId+"').remove();\">Sterge</a></td></tr></table>";
	html += '</div>';

	if (typeof(self.parent)!='undefined') {
		self.parent.$("#div_attr_ids_"+attrId).append(html);
		self.parent.$("#dialogBox").dialog("close");
	} else $("#div_attr_ids_"+attrId).append(html);
}

function removeDivGroup(htmlObj) {
	if (!$("*[id^='"+htmlObj+"_']").length) {
		$('#'+htmlObj).remove();
	}
}
function addDivItem(type,htmlObj,varName,id,value,objClass,removeParent) {
	//type - single => varname, 
	//	multiple => varname[]
	var html = '';
	var strVarName = '';
	switch (type)	{
		case 'single':
			var strVarName = varName;
			var strVarId = varName+'_'+id;
			if (typeof(self.parent)!='undefined') {
				if  (self.parent.$('*[id^='+htmlObj+'_]').length) {
					self.parent.$('#'+htmlObj).html("");
				}
			} else if ($('*[id^='+htmlObj+'_]').length) {
				$('#'+htmlObj).html("");
			}
			break;
		case 'multiple':
			var strVarName = varName+'[]';
			var strVarId = varName+'_'+id;					
			if (typeof(self.parent)!='undefined') {
				if  (self.parent.$('#'+htmlObj+'_'+id).length) {
					return;
				}
			} else if ($('#'+htmlObj+'_'+id).length) {
				return;
			}
			break;	
	}
	removeFunction = "$('#"+htmlObj+'_'+id+"').remove();";
	if (typeof(removeParent)!="undefined" && removeParent) {
		removeFunction+= "removeDivGroup('"+htmlObj+"');";
	}
	html += '<div id="'+htmlObj+'_'+id+'">';
	html += '<input type="hidden" name="'+strVarName+'" id="'+strVarId+'" value="'+id+'">';
//	html += '<input type="button" value="-" onclick="if (confirm(\'Esti sigur ca vrei sa stergi?\')) $(\'#div_attr_ids_'+attrId+'_'+attrValId+'\').remove();">&nbsp;'+unescape(attrValName);
	html += "<table width='100%' cellspacing=0 cellpadding=0 border=0 "+(typeof(objClass)!='undefined' ? "class='"+objClass+"'":"")+"><tr><td>"+unescape(value)+"</td><td width='50'><a href='javascript: void(0)' onclick=\"if (confirm('Esti sigur ca vrei sa stergi?')) {"+removeFunction+"}\">Sterge</a></td></tr></table>";
	html += '</div>';

	if (typeof(self.parent)!='undefined') {
		self.parent.$("#"+htmlObj).append(html);
	} else $("#"+htmlObj).append(html);
}

function openEditor(displayObj,hiddenObj) {
	$('#fckEditor').attr("src","fckeditor.html.php?displayObj="+displayObj+"&hiddenObj="+hiddenObj);
	$('#fckEditor').dialog("open");
}
function addToCart(e,id) {
    $('#opMessage').css('background-color','black');
    $('#opMessage').css('color','white');
    $('#opMessage').css('left',e.pageX);
	$('#opMessage').css('top',e.pageY+20);
	$('#opMessage').html("<img src='/images/js_effects/loading.gif'>");
	$('#opMessage').show();

	$.ajax({
	   type: "GET",
	   async: false,
	   url: urlPrefix+"/index.php?module=ajax&op=addToCart&id="+id,
	   success: function(msg){
		 tmp = msg.split("#");
		 $('#opMessage').html(tmp[0]);
		 $('#cartItems').html(tmp[1]);
		 setTimeout("$('#opMessage').hide()",2000);
//		 $('#opMessage').hide(2000);
	   }
	 });		
}