﻿
function Project(){
}

Project.charset="";
if ( typeof(document.charset)!=typeof(undefined) )
	Project.charset=document.charset;
else
 if ( typeof(document.characterSet)!=typeof(undefined) )
	Project.charset=document.characterSet;
Project.charset=Project.charset.toLowerCase();
if (Project.charset!="utf-8" &&  Project.charset!="utf8")
{
	alert("Warning:unable to detect UTF-8 charset, please try select manually in browser settings");
}

/*Project.nailw=100;
Project.nailh=100;*/
Project.Integrate=0;
Project.maxProdPage=3; 
Project.smallPictureDirName="pictures/thumbnail/";
Project.smallPictureDir="../"+Project.smallPictureDirName;

// End Configuration
//-------------------
//  Common function list
existInArray = function (arr,val){
  val=val.toString();
 for (var i=0;i<arr.length;i++)
   if (arr[i].toString() == val) return true;
 return false;
}

arrayIndex = function (arr,val){
  for (var i=0;i<arr.length;i++)
   if (arr[i] == val) return i;
 return -1;
}

indexOfObj = function(arr,obj){
 for (var i=0;i<arr.length;i++)
   if (arr[i].value == obj) return i;
 return -1;
}

//-----------------------------------------------
// Check the ENTER key - return true if pressed 
Project.checkEnter = function (e){ 
 var key=null;  
 if(e && e.which) 
  key = e.which;  
 else
  key = e.keyCode;
 return (key == 13);
}
//-----------------------------------------------
Project.sortNumber= function (a,b){ 
 return a-b;
}

Project.getFileExt= function(n){
 var dot = n.lastIndexOf("."); 
 if( dot == -1 ) return ""; 
 var ex = n.substr(dot+1,n.length); 
 return ex.toLowerCase(); 
}


isOptionOn= function (opt,value){
  return ((opt&value)!=0);
}
genOptionValue= function (opt,value){
  var val=0;
  for(var i=0; i<arguments.length; i++){
   val=val|arguments[i];	 
 } 
 return val; 
}

function staticLoadScript(){
 var str=""	
 for(var i=0; i<arguments.length; i++){
   var len= arguments[i].length;
   if (arguments[i].substr(len-2,2)=="ss")
	 str='<LINK rel="stylesheet" type="text/css" href="'+arguments[i]+'">';	 
   else
	 	str='<script src="'+ arguments[i]+ '" type="text/JavaScript"><\/script>';
   document.write(str);	
 }
}

﻿ 
function StringHash(arg){
  if (arg == "undefined" || arg=="" || arg==null)
	  this.str=null;
  else{
	  if (StringHash.validate(arg)) {		  
		 if (!arg.indexOf)
			this.str=new String(arg);
		 else
			this.str=arg;
	  }else{
			alert("StringHash Warning:"+StringHash.lastError+":"+arg);
	  }

  }
}

StringHash.sign="|";  // Delim between numbers
StringHash.lastError="";
StringHash.debug=false;

function StrHashFindObj(){
  this.arr_ind=null;  
  this.i=-1;   // index in arr_ind
  this.sum=0;  // summary of values
  this.sumInd=0;
  this.strL;
  this.strR;
}

StringHash.validate = function(s_temp){
 if (s_temp	 == "undefined" || s_temp=="" || s_temp==null) return true;
 if (!s_temp.indexOf)
		s_temp=new String(s_temp);

 var arr=new Array(0);
 arr['lInd'] = s_temp.indexOf(StringHash.sign)+1;
 if (arr['lInd']==0) { StringHash.lastError="Delimiter not found"; return false; }
 var tmp_val=s_temp.substring(0,arr['lInd']-1);
 if ( isNaN(tmp_val)) { StringHash.lastError="start ind propblem(ind="+tmp_val+")"; return false; }
 arr['mInd'] = Number(tmp_val)+arr['lInd'];
 arr['strL']= s_temp.substring(arr['lInd'],arr['mInd']);
 
 arr['strR']= s_temp.substring(arr['mInd'],s_temp.length);
 
 var arr_ind=arr['strL'].split(StringHash.sign);
 //if (StringHash.debug) alert(arr['strL']);
 var sum=0;     
 for (var i=0;i<arr_ind.length;i++)
 {
     if ( isNaN(arr_ind[i]) ) { StringHash.lastError="ind problem(ind="+arr_ind[i]+")"; return false; }
	 //if (StringHash.debug) alert(arr_ind[i]);
     sum+=Number(arr_ind[i]);
 }
 
 if (sum!=arr['strR'].length){ StringHash.lastError="match faiied "+sum+"!="+arr['strR'].length;  return false; }
 //if (StringHash.debug) alert("Done ok:"+arr['strR'].length);	
 return true;
}

StringHash.createFromArray = function(arr){
  var hash=new StringHash();
  for (var prop in arr) {
	  hash.add(prop,arr[prop]);
  }
  return hash;
}

//---------------------------------------------------------------------||
// RETURNS:  updated string                                            ||
// PURPOSE:  add NAME and Value to STR                                 ||
// Exampele: 10| 5| 4| 5| 4| Name1Val1Name2Val2                        ||  
//---------------------------------------------------------------------||
function addToStrHash01(name,val){
 name=new String(name);
 val=new String(val);
 if (name!="") {
  if (this.str!=null) {
    this.remove(name);
    var arr = this.updateIndexes();
	this.str = arr['strL']+name.length+
			StringHash.sign+val.length+StringHash.sign;
    this.str= this.str.length+StringHash.sign+this.str+arr['strR']+name+val;
  } else {
    this.str = name.length+StringHash.sign+val.length+StringHash.sign;
    this.str= this.str.length+StringHash.sign+this.str+name+val;
  }
 }else{ 
		alert("StringHash warning: blank name");
 }
 
 return this.str;
}
 
//---------------------------------------------------------------------||
// RETURNS:     updated string                                         ||
// PURPOSE:     remove NAME and Value from STR,searhing by name        ||
//---------------------------------------------------------------------||
function removeFromStrHash01(name)
{
  var fObj = this.findValue(new String(name));
  if (fObj!=null)
  {
     var lInd = fObj.ind+Number(fObj.arr_ind[fObj.i+1])+
					Number(fObj.arr_ind[fObj.i+2]);
     var strRl=fObj.strR.substring(0,fObj.ind);
     var strRr=fObj.strR.substring(lInd,fObj.strR.length);
     fObj.strR=strRl+strRr;  
     var strLl=fObj.strL.substring(0,fObj.sumInd);
     lInd = fObj.sumInd+fObj.arr_ind[fObj.i+1].length+
			fObj.arr_ind[fObj.i+2].length+2;
     var strLr=fObj.strL.substring(lInd,fObj.strL.length);
     fObj.strL=strLl+strLr;  
     this.str = fObj.strL.length+StringHash.sign+fObj.strL+fObj.strR; 
  }

  return this.str;
}
 
function toStringStrHash01()
{
  if (this.str==null) return "";
  return this.str;
}
//---------------------------------------------------------------------||
// RETURNS:     Value                                                  ||
// PURPOSE:     return VALUE by NAME                                   ||
//---------------------------------------------------------------------||
function getStrHash01(name){
 
  var findObj = this.findValue(new String(name));
  if (findObj!=null) {
    findObj.ind += Number(findObj.arr_ind[findObj.i+1]);
	return  findObj.strR.substring(findObj.ind,findObj.ind+Number(findObj.arr_ind[findObj.i+2]));
  }
 return null;
}

 //---------------------------------------------------------------------||
// Remove by Index
//----------------------------------------------------------------------||
StringHash.prototype.removeByIndex = function (ind){
 var arr = this.getByIndex(ind);
 if (arr!=null)
	  this.remove(arr[0]);
}
 //---------------------------------------------------------------------||
// RETURNS:     object with find results                                ||
//----------------------------------------------------------------------||
StringHash.prototype.findValue = function (name){
  var val=new StrHashFindObj();
  
  if (this.str!=null && name!="")
  {
    var arr = this.updateIndexes();
	val.strL = arr['strL'];
    val.strR = arr['strR'];
	val.arr_ind=val.strL.split(StringHash.sign);
 
    val.ind = val.strR.indexOf(name);
    val.sum=0;
    val.i=-1;

    while (val.ind!=-1)
    {
      while (val.sum<val.ind || val.i%2==0 ) // find it
	  { 
	      val.i++;
	      val.sum+=Number(val.arr_ind[val.i]);
	      val.sumInd+=(val.arr_ind[val.i]).length+1;
	  }
 
      if (val.sum==val.ind && (val.i%2==1||val.i==-1) &&
		val.strR.substring(val.ind,val.ind+Number(val.arr_ind[val.i+1]))==name ) 
	  {
	      return val;
	  }

	  val.ind = val.strR.indexOf(name,val.ind+1);
    }
  }
 return null;
}
//---------------------------------------------------------------------||
// RETURNS:     return Indexes                                         ||
//---------------------------------------------------------------------||
function updateLRIndexStrHash01(){
 var arr=new Array(0);
  arr['lInd']=-1;
  arr['mInd']=-1;
  arr['strL']="";
  arr['strR']="";
  if (this.str!=null) {
     arr['lInd'] = this.str.indexOf(StringHash.sign)+1;
     arr['mInd'] = Number(this.str.substring(0, arr['lInd']-1) )+arr['lInd'];
	 arr['strL']= this.str.substring(arr['lInd'],arr['mInd']);
	 arr['strR']= this.str.substring(arr['mInd'],this.str.length);
  }
  return arr;
}
//---------------------------------------------------------------------||
// RETURNS:   2 element array:NAME and VALUE                           ||
// PURPOSE: return NAME and VALUE by INDEX                             ||
//---------------------------------------------------------------------||
function getByIndexStrHash01(index){
  var val=null;
  if (this.str!=null && index>=0 )
  {
    var arr = this.updateIndexes();
    var arr_ind=arr['strL'].split(StringHash.sign);
    
    if (index*2<arr_ind.length-1)
    {   
      var ind=0;
      for (var i=0;i<index*2;i++)
      {
        ind+=Number(arr_ind[i]);
      }
      var i1 = Number(arr_ind[index*2]);
      var i2 = Number(arr_ind[index*2+1]);
      val = new Array(arr['strR'].substring(ind,ind+i1),
							arr['strR'].substring(ind+i1,ind+i1+i2) );
    }
 
  }
  return val;
 
}
 
StringHash.prototype.updateIndexes=updateLRIndexStrHash01;
 
//------------------------ USER INTERFACE
StringHash.prototype.debugShowAll=function(){
  var j=0;
  var arr = this.getByIndex(j++);	
  var str="";
  while (arr!=null ) {
	str+=arr[0]+"  :  "+arr[1]+"\n\n";
	arr = this.getByIndex(j++);	
  }
  alert("StringHash Debug:\n"+str);
}

StringHash.prototype.moveToInd=function(indFrom,indTo){
  if (indFrom==indTo) return;
  var strHash=new StringHash();
  var j=0;
  var arr = this.getByIndex(j);	
  var arr1 = this.getByIndex(indFrom);	
  while (arr!=null ) {
	if (indFrom>indTo){  
		if (j==indTo)  strHash.add(arr1[0],arr1[1]); 
    	if(j!=indFrom) strHash.add(arr[0],arr[1]); 
	}else{
    	if(j!=indFrom) strHash.add(arr[0],arr[1]); 
		if (j==indTo)  strHash.add(arr1[0],arr1[1]); 
    }
    j++;
    arr = this.getByIndex(j);	
  }
  this.str=strHash.str;
}


StringHash.prototype.count=function(){
  var j=0;
  var arr = this.getByIndex(j);	
  while (arr!=null ) {
    j++;
    arr = this.getByIndex(j);	
  }
  return j;
}


//---------------------------------------------------------------------||
// RETURNS:     updated string                                         ||
// PURPOSE:     remove NAME and Value from STR,searhing by name        ||
//---------------------------------------------------------------------||
StringHash.prototype.remove=removeFromStrHash01;
//---------------------------------------------------------------------||
// RETURNS:  updated string                                            ||
// PURPOSE:  add NAME and Value to STR                                 ||
// Exampele: 10| 5| 4| 5| 4| Name1Val1Name2Val2                        ||  
//---------------------------------------------------------------------||
StringHash.prototype.add=addToStrHash01;
//---------------------------------------------------------------------||
// RETURNS:  string representation of HashString                       ||
//---------------------------------------------------------------------||
StringHash.prototype.toString=toStringStrHash01;
//---------------------------------------------------------------------||
// RETURNS:     Value                                                  ||
// PURPOSE:     return VALUE by NAME                                   ||
//---------------------------------------------------------------------||
StringHash.prototype.get=getStrHash01;
//---------------------------------------------------------------------||
// RETURNS: 2 element array:NAME and VALUE                             ||
// PURPOSE: return NAME and VALUE by INDEX                             ||
//---------------------------------------------------------------------||
StringHash.prototype.getByIndex=getByIndexStrHash01;
//----------------------------------------------------------------------
//StringHash.prototype.moveToInd  - move to index﻿
function Url(){
}

Url.removeProtocol=function(url){
   var ind=url.indexOf("://");
   if (ind!=-1)
		url=url.substring(ind+3,url.length);
   return url;
}

Url.isSecure= function (url){
 var ind=url.indexOf("://");
   if (ind==-1 )return false;
   ind--;
   if (url.charAt(ind)=='s' || url.charAt(ind)=='S') return true;
   return false;
}

Url.setProtocol = function (url,protocol)
{
	return protocol+Url.removeProtocol(url);
}

Url.getQueary = function (url)
{
   if (url!=""){
     var arg_arr=url.split("?");
	 if (arg_arr.length>0 && typeof(arg_arr[1]) != typeof(undefined) ) {
		 return arg_arr[1];
	 }
   }
   return "";
}


Url.getURLValue = function (srch,name01)
{
   if (srch!="") {
     var arg_arr=srch.split("?")[1].split("&");
	 for (var j=0;j<arg_arr.length ;j++){
		var val=arg_arr[j].split("=");
		if (val[0]==name01){
			 //alert("val:"+unescape(val[1]));
			 return unescape(val[1]);
		}
	 }
   }
   return null;
}
//Return value from current location
Url.getCurrentValue = function(name01){
   return Url.getURLValue(location.search.toString(),name01);
}


Url.getDomain = function(ret){
   ret=Url.removeProtocol(ret);
   var ind=ret.indexOf("/");
   if (ind!=-1)
		ret=ret.substring(0,ind);
   return ret;
	
}


Url.getLocation = function(ret){
   var argind=ret.indexOf("?");
   var ind;
   if (argind==-1){
	ind=ret.lastIndexOf("/");	
   }else{
     ind=ret.lastIndexOf("/",argind);	
   }
   if (ind!=-1)
		ret=ret.substring(0,ind+1);
   return ret;
	
}

// Get Current Locatin without FILENAME
Url.getCurrentLocation = function(){
   //alert(location.pathname.toString().split('\\').reverse()[0]);
   var ret = location.href.toString();
   return Url.getLocation(ret);
}

// Get FILENAME
Url.getFile = function(url){
   return url.split('/').reverse()[0];
}

Url.removeParams=function(url){
   var ind=url.indexOf("?");
   if (ind!=-1)
		url=url.substring(0,ind);
   return url;
}


Url.getCurLocNoProtocol = function(){
   return Url.removeProtocol(Url.getCurrentLocation());
}


Url.go = function(url,newWindowName){
  if (typeof newWindowName === 'string')
	window.open(url,newWindowName)
  else
	location.href=url;
}


Url.curLoc = function(){
  return location.href;
}


Url.setURLvalue = function (url,name,val){ 
  if (name==null || name=="undefined" || name=="")
		return url;
	 url=Url.delURLvalue(url,name);
	 if ( url.indexOf("?")==-1 )
		  url+="?";
	 else
		  url+="&";
  return (url+name+"="+val);
}



Url.delURLvalue = function (url,name){ 
	// case ..?name=x
	var ind_start=url.indexOf("?"+name+"=");
	if (ind_start!=-1){
		var ind_end=url.indexOf("&",ind_start+1);

		if (ind_end==-1)
			 return url.slice(0,ind_start);
		 return url.slice(0,ind_start+1)+url.slice(ind_end+1);
	}


	// case ..?...&name=x&..
	ind_start=url.indexOf("&"+name+"=");
	if (ind_start==-1)return url; // not found

	var ind_end=url.indexOf("&",ind_start+1);
	if (ind_end==-1)
			 return url.slice(0,ind_start);
	return url.slice(0,ind_start+1)+url.slice(ind_end+1);

}

Url.isValid = function (url){ 
	var rx = new RegExp("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-\\+ ./?%:&=#\\[\\]]*)?"); 
	var matches = rx.exec(url); 
	return (matches != null && url == matches[0]); 	
}

//alert("DEBUG:LIST included");

function List()
{
  this.list = new Array(0);
  for (var i=0;i<arguments.length;i++)
	{
	   this.list[ i ] = arguments[i];
	}
}

List.prototype.toArray  = function (){
	return this.list;
}

List.prototype.add  = function (){

  for (var i = 0; i < arguments.length; ++i) {
    this.list[ this.list.length ] = arguments[i];
  }
}

List.prototype.set = function (ind,element){
    this.list[ ind ] = element;
}


List.prototype.size = function (){
 return  this.list.length;
}

List.prototype.get = function (index){
 if (index<this.list.length)
	 return  this.list[index];
  return null;
}


List.prototype.remove = function (element){
  return this.removeByIndex(this.find(element));
}


List.prototype.removeByIndex = function (found){

  if (found!=-1)   
  {
    this.list = (new Array()).concat(this.list.slice(0,found),this.list.slice(found+1,this.list.length));	 
  }
  return found;
}


List.prototype.find  = function (element){
  var found=-1;
  var ind=0;
  var strEl = element.toString(); 

  while (ind<this.list.length && found==-1)
  {
    if (this.list[ind].toString() == strEl ){ 
  	  found = ind; 
    }
    else{ 
    	  ind++; 
    }
	
  }

  return found;
}

//--------- Not tested ----------
List.prototype.convertToStr = function(){

  var pL="";
  var pR="";
  var sign="|";
  var str="";

  for (var ind=0;ind<this.list.length;ind++)
  {
   pL+=this.list[ind].toString().length+sign;
   pR+=this.list[ind].toString();     
  
  }
  str=pL.length+sign+pL+pR;
  return str;

}

List.convertToList = function(str){
 var sign="|";
 var list = new List();


 var lInd = str.indexOf(sign)+1;
 var mInd = Number( str.substring(0,lInd-1) )+lInd;
 
 var strL = str.substring(lInd,mInd);
 var strR = str.substring(mInd,str.length);
 var arr_ind=strL.split(sign);
 var j=0;
 for (var i=0;i<arr_ind.length-1;i++)
  {
    var ni=Number(arr_ind[i]); 
    list.add( strR.substring(j,j+ni) );
    j+=ni;
  }

 return list;

}
﻿
function DummyCookies(cookieName,length,isRemove){
 this.CookieName01=cookieName;   
 this.len=0;
 if (isRemove){
 	this.removeAll(); 
 }
 if ( !DummyCookies.isAlive(cookieName) ){
	  if (length && DummyCookies.getFreeSpace()>=length){
		//alert("Cookie created");
	  } else {
		  alert("Error:can't allocate cookie space");
		  return;
	  }
 }else{
	 if (length){
		 if (DummyCookies.size(cookieName)>length){
			alert("Error:Can't realocate cookie,not enoth size");
			return;
		 }
	  }else{
	     length = DummyCookies.maxSize;
	  }
 }
 this.len=length;
}

DummyCookies.expires=null;
DummyCookies.path=null;
DummyCookies.domain=null;
DummyCookies.secure=null;
DummyCookies.maxSize=4000; // Cookie lenght max = 4000;
DummyCookies.strCookiesDis="Please enable your cookies";
DummyCookies.strNoFreeSpace="Cookies warning:No Free Space";
//---------------------------------------------------------------------||
// RETURNS:     length	in characters	                               ||
// PURPOSE:     get Cookie free space								   ||	
//---------------------------------------------------------------------||
DummyCookies.prototype.getFreeSpace = function (){
  return this.len-DummyCookies.size(this.CookieName01);
}
//---------------------------------------------------------------------||
// RETURNS:     length	in characters	                               ||
// PURPOSE:     get global free space								   ||	
//---------------------------------------------------------------------||
DummyCookies.getFreeSpace = function (){
  var size=DummyCookies.getMainHash().toString().length;
  return DummyCookies.maxSize-size;
}
//---------------------------------------------------------------------||
// RETURNS:     null												   ||
// PURPOSE:     Set Cookie parametres								   ||	
//---------------------------------------------------------------------||
DummyCookies.setParam = function (expires,path,domain,secure){
 DummyCookies.expires=expires;
 DummyCookies.path=path;
 DummyCookies.domain=domain;
 DummyCookies.secure=secure;
}
//---------------------------------------------------------------------||
// RETURNS:     checkes if Cookie exist                                ||
// PURPOSE:     return true or false								   ||	
//---------------------------------------------------------------------||
DummyCookies.isAlive = function (name){
  var c_hash = DummyCookies.getCookiesHash();
  var str = c_hash.get(name);
  if (str==null)  return false;
  return true;
}
//---------------------------------------------------------------------||
// RETURNS:     checkes if Cookie exist and
// PURPOSE:     return cookie length
//---------------------------------------------------------------------||
DummyCookies.size = function (name){
  var c_hash = DummyCookies.getCookiesHash();
  var str = c_hash.get(name);
  if (str==null)  0;
  return escape(str).length;
}

//---------------------------------------------------------------------||
// RETURNS:     Unescaped Cookie Value                                 ||
// PURPOSE:     Get array [name,val]  by index						   ||
//---------------------------------------------------------------------||
DummyCookies.prototype.getByIndex = function (ind){
  return DummyCookies.getByIndexCookie(this.CookieName01,ind);
}

DummyCookies.getByIndexCookie = function (cookieName,ind){
  var strH = DummyCookies.getCookieHash(cookieName);
  var val=strH.getByIndex(ind);
  strH=null;
  return val;
}

//---------------------------------------------------------------------||
// Delete all dummy cookies (Destroy Cookie)
//---------------------------------------------------------------------||
DummyCookies.prototype.removeAll = function (){
 return DummyCookies.setCookieHash(this.CookieName01,"");
}
//---------------------------------------------------------------------||
// Delete dummy cookie
//---------------------------------------------------------------------||
DummyCookies.prototype.remove  = function (item){
  DummyCookies.removeCookie(this.CookieName01,item);
}

DummyCookies.removeCookie  = function (cookieName,item){
  var strH = DummyCookies.getCookieHash(cookieName);
  strH.remove(item);
  return DummyCookies.setCookieHash(cookieName,strH.toString());
}

//---------------------------------------------------------------------||
// RETURNS: String representation of Cookie in StringHash format       ||
//---------------------------------------------------------------------||
DummyCookies.serialize = function (){
  var mcookie = DummyCookies.getMainHash();
  return mcookie.toString();
}
DummyCookies.unserialize = function (str){
  return DummyCookies.setMainHash(str);
}
//---------------------------------------------------------------------||
// RETURNS:     Unescaped Cookie Value                                 ||
// PURPOSE:     Get a specific value from a cookie   - dummy           ||
//---------------------------------------------------------------------||
DummyCookies.getCookie= function (cookieName,item){
  var strH = DummyCookies.getCookieHash(cookieName);
  var val=strH.get(item);
  strH=null;
  return val;
}

DummyCookies.prototype.get = function (item){
  return DummyCookies.getCookie(this.CookieName01,item);
}

//---------------------------------------------------------------------||
// RETURNS:     true if success,else false							   ||
// PURPOSE:     Set a specific value to a cookie   - dummy             ||
//---------------------------------------------------------------------||
DummyCookies.prototype.set = function (item,newvalue){
  return DummyCookies.setCookie(this.CookieName01,item,newvalue);
} 

DummyCookies.setCookie = function(cookieName,item,newvalue){
  if (!isNaN(item))
	  item=new String(item);

  if (item=="" || item==null){
     alert("Error:empty cookie name:"+item);
     return;
  }
  var strH = DummyCookies.getCookieHash(cookieName);
  strH.add(item,newvalue);
  
  return DummyCookies.setCookieHash(cookieName,strH.toString());
}

//-------------------------------------------
DummyCookies.setCookieHash = function (cookieName,hash){
  //alert(hash);
	var c_hash = DummyCookies.getCookiesHash();
	//alert(c_hash);
  c_hash.add(cookieName,hash);
  //alert(c_hash.toString());
  return DummyCookies.setCookiesHash(c_hash);
}

DummyCookies.getCookieHash = function(cookieName){
  var c_hash = DummyCookies.getCookiesHash();
  return new StringHash(c_hash.get(cookieName));
}
//-------------------------------------------
DummyCookies.setCookiesHash =function (hash){
  var mcookie = DummyCookies.getMainHash();
  mcookie.add("CH",hash.toString());
  return DummyCookies.setMainHash(mcookie);
}

DummyCookies.getCookiesHash=function(){
  var mcookie = DummyCookies.getMainHash();
  var c_hash = new StringHash(mcookie.get("CH"));
  return c_hash;
}
//-------------------------------------------
DummyCookies.getMainHash=function (){
  var mcookie = new StringHash(GetCookie("VC"));
  //if (mcookie.isError()) alert(mcookie.getError());
  return mcookie;
}

DummyCookies.setMainHash=function (mcookie){
  var newCookie = mcookie.toString();
  var newCookieL=(escape(newCookie)).length;
  strH=null;
  if ( DummyCookies.maxSize >= newCookieL ){
	  SetCookie("VC",newCookie,DummyCookies.expires,
		   DummyCookies.path,DummyCookies.domain,DummyCookies.secure);
      // Cookie enable test...
	   if ( GetCookie("VC") != newCookie){
		alert(DummyCookies.strCookiesDis);
		//alert(cookieName+":"+GetCookie(cookieName)+"!="+newCookie);
		return false;
	   }
  }else{
	alert(DummyCookies.strNoFreeSpace);
	return false;
  }

 return true;
}
//			------------  Real cookies -------------
//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}
//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
//function FixCookieDate (date) {
//   var base = new Date(0);
//   var skew = base.getTime();
//   date.setTime (date.getTime() - skew);
//}
//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}
//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
  
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}
//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ){
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 99-Jan-70 00:00:01 GMT";
   }
}

/*if (typeof(DummyCookies)!= typeof(undefined))
{
 DummyCookies.ul = new DummyCookies("!ul!",300); 
 if (DummyCookies.ul.get('0')==null)
  {
	  var rstr='document.referrer';
	  rstr=rstr.toLowerCase();
	  if (rstr.indexOf('blocked')==-1 && rstr.indexOf('document.')==0)
	  {
		  rstr=document.referrer;
		  if (rstr.length>255)rstr=rstr.substring(0,251);
		  DummyCookies.ul.set('0',rstr+"...");
	  }
  }
 
 if (typeof(Url)!= typeof(underfined) && DummyCookies.ul.get('1')==null )
  {
	DummyCookies.ul.set('1',Url.getCurrentValue('ref'));
  }
}*/


function MultiLang(){
}
MultiLang.lang=0;

MultiLang.get = function (str){
return MultiLang.getByLang(str,MultiLang.lang);
}

MultiLang.getByLang = function (str,lng){
 if ( StringHash.validate(str) ){
   var hash=new StringHash(str);
   return MultiLang.getByLangHash(hash,lng);
  } 
 return str;
}

MultiLang.getByLangHash = function (hash,lng){
 var s=hash.get(lng);
 if (s==null){
	 s=hash.get(0);
	 if (s==null) s="";
 }
 return s;
}

MultiLang.getByHashPlain = function (hash,lng){
 var s=hash.get(lng);
 if (s==null) s="";
 return s;
}
﻿
function Charge(id,section,name,type,cost1,cost2,cost3,addtype,condpointer){ 
  this.arr = new Array();
  this.arr['id']=id;
  this.arr['section']=section; //1 - shipping 2 - tax
  this.arr['name']=name;
  this.arr['type']=type; 
  this.arr['cost1']=cost1;
  this.arr['cost2']=cost2;
  this.arr['cost3']=cost3;
  this.arr['addtype']=addtype;
  this.arr['condpointer']=condpointer;
}

//Charge.SP_PROD_PROP="!#!spc!#!";
Charge.SP_SHIP="!#!shp!#!";
Charge.SP_QUOTE="!#!qte!#!";
Charge.SP_QNT="!#!qnt!#!";
Charge.SP_ADDPRICE="!#!spr!#!"; //select
Charge.SP_CHECKBOXPRICE="!#!spx!#!";

Charge.CHARGE_LIST=new Array(0);

Charge.createSP_ADDPRICE= function (num){
  return "!#!spr"+num+"!#!";
}

Charge.isSP_ADDPRICE= function (str){
  return str.indexOf("!#!spr")==0;
}

Charge.createSP_CHECKBOXPRICE= function (num){
  return "!#!spx"+num+"!#!";
}

Charge.isSP_CHECKBOXPRICE= function (str){
  return str.indexOf("!#!spx")==0;
}


Charge.isSpecial= function (name){ 
 if ( name.indexOf("!#!")==0 && name.indexOf("!#!",3) == name.length-3  )
	 return true;
 return false;
}

Charge.getList= function (){ 
	 return Charge.CHARGE_LIST;
 }
Charge.addToList=function (item){ 
	 Charge.CHARGE_LIST[Charge.CHARGE_LIST.length]=item;
 }

Charge.prototype.get = function (arg){
  return this.arr[arg];
}
Charge.prototype.set = function (name,val){
  this.arr[name]=val;
}
Charge.prototype.getName = function (){
  return this.arr['name'];
}
Charge.prototype.setName = function (name){
  this.arr['name']=name;
}
Charge.prototype.getId = function (){
  return this.arr['id'];
}
Charge.prototype.getType = function (){
  return this.arr['type'];
}
Charge.prototype.setType = function (type){
  this.arr['type']=type;
}

Charge.countInSection=function (section){
  var count=0;
   for (var i=0;i<Charge.CHARGE_LIST.length;i++)
		if (Charge.CHARGE_LIST[i].get('section')==section) count++;
  return count;
}

Charge.getInSection=function (section){
  var list=new List()
   for (var i=0;i<Charge.CHARGE_LIST.length;i++)
		if (Charge.CHARGE_LIST[i].get('section')==section)
	      list.add(Charge.CHARGE_LIST[i]);
  return list;
}

Charge.getById=function (idc){
   for (var i=0;i<Charge.CHARGE_LIST.length;i++)
		if (Charge.CHARGE_LIST[i].getId()==idc) return Charge.CHARGE_LIST[i];
	return null;
}

Charge.prototype.initForm=function (form,arr)
{
  for (var prop in this.arr) {
	if (form.elements[prop]!=null){
		if (!existInArray(arr,prop))
			  form.elements[prop].value=this.arr[prop];
	} else {
	    alert("Error,cant init:"+prop);
	}
  }
}

Charge.prototype.init=function (form,arr){
  for (var prop in this.arr)
	if (form.elements[prop]!=null){
		if (!existInArray(arr,prop))
			  this.arr[prop]=form.elements[prop].value;
	  }
	else
	  alert("Error,cant init:"+prop);
 
}

Charge.prototype.getAs2DArray=function(){
	return this.arr;
}
Charge.prototype.initFromHash=function(hash){
  for (var prop in this.arr)
	  this.arr[prop]=hash.get(prop);
}

//- For global
Charge.prototype.calc = function (){
  return this.getResult(ShoppingCart.subtotal);
}

Charge.prototype.getResult= function (total){
  if ( this.checkCondition(total) )
	  return this.applyAction(total);
  return 0;
}

Charge.prototype.checkCondition= function (total){
  var cond = Charge.getConditionFromType( this.getType() );
  if (cond==1) return true;
  if (cond==2 ){
	if (this.get('cost1')*Project.mconvert<=total && this.get('cost2')*Project.mconvert>total)
		return true;
  }
  if (cond==3 ){ return true; } //in zone

  return false;
}

Charge.prototype.applyAction= function (total){
  var act = Charge.getActionFromType( this.getType() );
  
  var ret=0;
  // Add value
  if (act==1 || (act>=5 && act<=15)) ret=this.get('cost3')*Project.mconvert; // 5-15 - for UPS
  // Multiply 
  if (act==2) {  ret=this.get('cost3')*total;  }
  
  if (act==3) { //For each product (NumProd*A*Weight)
	 var sum=0;
	 var cost1=this.get('cost1');
	 var ids=Product.getIdsFromCart();
	 for (var i=0;i<ids.length;i++){
		var nInCart=Product.countInCart(ids[i]);
		var pr=Product.getById(Product.getRealId(ids[i]));
		var qval=pr.getWeight();
		//alert(qval+":"+cost1+":"+nInCart);
		sum+=qval*cost1*nInCart;
	  }
	 ret=sum*Project.mconvert; 
  }

 if (act==4) { //value=A+(numberProd+B)*C + SP_SHIP
	 var sum=0;
	 var ids=Product.getIdsFromCart();
	 var nProd=0;
	 for (var i=0;i<ids.length;i++){
		var nInCart=Product.countInCart(ids[i]);
		nProd+=nInCart;
		var pr=Product.getById(Product.getRealId(ids[i]));
		var j=0;
		var qval=pr.getMultipropVal(Charge.SP_SHIP);
		if (qval!=null)
			sum+=Number(qval)*nInCart;
	  }

	 ret=this.get('cost1')+(nProd+this.get('cost2'))*this.get('cost3')+sum;
	 ret=ret*Project.mconvert;

 }

  if (act==16) { //MAX(SP_SHIP)
	 var sum=0;
	 var ids=Product.getIdsFromCart();
	 for (var i=0;i<ids.length;i++){
		var pr=Product.getById(Product.getRealId(ids[i]));
		var qval=pr.getMultipropVal(Charge.SP_SHIP);
		if (qval!=null){
			qval=Number(qval);
			if (sum<qval)
				sum=qval;
		}
	  }
	 ret=sum*Project.mconvert;

} 
 
 return ret;

}

Charge.convertToType=function (condition,act){
  return (condition<<8) | act;
}

Charge.getConditionFromType=function (type){
  return type>>>8;
}
Charge.getActionFromType=function (type){
  return type&255;
}
﻿function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

//  EVENTS & DOM 

var Dom = {
  loadXML: function(mess) {
  var xmlobject;	
  try{ //IE
	  xmlobject=new ActiveXObject("Microsoft.XMLDOM");
  	  xmlobject.async="false";
  	  xmlobject.loadXML(mess);
  	}catch(e) {
    	 try{ //Firefox, Mozilla, Opera, etc.
	        xmlobject=new DOMParser();
        	xmlobject=xmlobject.parseFromString(mess,"text/xml");
    	} catch(e) {
       	alert(e.message)
    	}
  	}
  	return xmlobject;	  
  },

  get: function(el) {
    if (typeof el === 'string') {
      return document.getElementById(el);
    } else {
      return el;
    }
  },
  add: function(el, dest) {
    var el = this.get(el);
    var dest = this.get(dest);
    dest.appendChild(el);
  },
  remove: function(el) {
    var el = this.get(el);
    el.parentNode.removeChild(el);
  }
  };
  var Event = {
  add: function() {
    if (window.addEventListener) {
      return function(el, type, fn) {
        Dom.get(el).addEventListener(type, fn, false);
      };
    } else if (window.attachEvent) {
      return function(el, type, fn) {
        var f = function() {
          fn.call(Dom.get(el), window.event);
        };
        Dom.get(el).attachEvent('on' + type, f);
      };
    }
  }()
 };




function Html(){
}



/* AJAX consider using encodeURIComponent in values*/
//true (asynchronous) / false (synchronous).
XMLHttp = function(isAsynch) {
  this.xml = Html.getXmlHttp();
  if (this.xml==null) { 
	  alert("Error:Cant init XMLHTTP");
	  return;
  }
  this.synch=isAsynch;
  this.busy=false;
}
XMLHttp.prototype.getResp = function() {
 return this.xml.responseText;
}

XMLHttp.prototype.get = function(url,call_back_func) {
 if (this.busy==true) return false;
 this.call_back=call_back_func;
 this.busy=true;	
 var self=this;
 this.xml.onreadystatechange = function() {
     self.processRequest();
  }
  this.xml.open('GET', url, this.synch);
  this.xml.send(null);
  
  return true;
}

// function arguments: url,call_back_func, data(name=val&name1=val1...)
XMLHttp.prototype.post = function(url,call_back_func,data) {
 if (this.busy==true) return false;
	
 this.call_back=call_back_func;
 this.busy=true;	
 var self=this;
 this.xml.onreadystatechange = function() {
     self.processRequest();
  }
 
 this.xml.open("POST", url, this.synch); 
 this.xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
 this.xml.send(data);
 
 return true;
}

// function arguments: url,call_back_func, [name,val],[name1,val1]
XMLHttp.prototype.postArg = function(url,call_back_func) {
 var data=""; 
 for(var i=2; i<arguments.length; i+=2){
	 if (data!="") data+="&";
     data += arguments[i]+"="+arguments[i+1]; 	
 }
 this.post(url,call_back_func,data);
}

XMLHttp.prototype.postForm = function(url,call_back_func,form) {
 var data=""; 
  for (var i=0;i<form.elements.length;i++){
	 if (trim(form.elements[i].name)!=""){
	 	if (data!="") data+="&";
	 	data+=form.elements[i].name+"="+form.elements[i].value;
 	}
  }
  this.post(url,call_back_func,data);
}

XMLHttp.prototype.processRequest = function() {
  if (this.xml.readyState == 4 || !this.synch ) {
    if (this.xml.status == 200) {
	   this.call_back(this.xml.responseText);
    }else{
       this.call_back(null);
    }
   	this.busy=false;  
  }
}



Html.getXmlHttp=function(){
	var xmlHttp=null;
	try{
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }catch (e){
		  // Internet Explorer
		  try{
		    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		   }catch (e){
			    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		    }
	  }
	return xmlHttp;
}

/* END AJAX */	


function openModal(url,width,height){
 if (window.showModalDialog) {
    return window.showModalDialog(url,window.self,"dialogWidth:"+width+"px;dialogHeight:"+height+"px");
 }else{
    return window.open(url,window.self,'height='+height+',width='+width+',toolbar=no,directories=no,status=no,scrollbars=no,resizable=no,modal=yes');
 }
}

Html.getElement=function(id){
  return document.getElementById(id);
}
//---------------------------------
// Show or hide element
Html.show_hide_EL=function(id,isShow){
 var hidden='visible';
 if (isShow==0) hidden='hidden';
 try{
 	var el=Dom.get(id);
 	el.style.visibility = hidden;
 }catch(err){}
}

//---------------------------------
// Display or not the element
Html.displayElement=function(id,isShow){
 var hidden='block';
 if (isShow==0) hidden='none';
 try{
 	var el=Html.getElement(id);
 	el.style.display= hidden;
 }catch(err){}
}
Html.isDisplay=function(element){
  return (element.style.display.toLowerCase() == 'block' );
}


Html.isHidden=function(element){
  return element.style.visibility.toLowerCase() == 'hidden';
}
//----------------------------
Html.hideElement=function(id){
	Html.show_hide_EL(id,0);
 }
//----------------------------
Html.showElement=function(id){
	Html.show_hide_EL(id,1);
 }
 
Html.disableElement=function(id){
 var el=Html.getElement(id);
 el.disabled = true;
}
Html.enableElement=function(id){
 var el=Html.getElement(id);
 el.disabled = false;
}

//-------- Elements with CSS classes -----------
Html.changeClass= function(el,remclass,addclass){
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != remclass && cls[--i] != addclass) ar[ar.length] = cls[i];
	}
	ar[ar.length] = addclass;
	el.className = ar.join(" ");
}

Html.removeClassById= function(id,classname){
 Html.removeClass(Html.getElement(id),classname);
}
//swap or swap back
Html.swapClass = function(el, className1, className2) {
	if (!(el && el.className)) {
		return;
	}
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = 0; i < cls.length;i++) {
		if (cls[i] != className1 && cls[i] != className2) {
			ar[ar.length] = cls[i];
		}else{
			if (cls[i] == className1)
				ar[ar.length] = className2;
			else
				ar[ar.length] = className1;
		}
	}
	el.className = ar.join(" ");
};


Html.removeClass = function(el, className) {
	if (!(el && el.className)) {
		return;
	}
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != className) {
			ar[ar.length] = cls[i];
		}
	}
	el.className = ar.join(" ");
};
//set class if not exist
Html.addClass = function(el, className) {

	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != className) {
			ar[ar.length] = cls[i];
		}
	}
	ar[ar.length] = className;
	el.className = ar.join(" ");
	
};

//-------- END Elements with CSS classes -----------


Html.TEXT ="TEXT";
Html.TEXTAREA ="TEXTAREA";
Html.RADIO ="RADIO";
Html.CHECKBOX ="CHECKBOX";
Html.BUTTON ="BUTTON";
Html.SELECT ="SELECT";
Html.UTF8STRING ="UTF8STRING";
Html.HIDDEN ="HIDDEN";
Html.OPTION ="OPTION";
Html.FORM ="FORM";



Html.checkElement=function(el){
 if (el==null || typeof(el)==typeof(underfined) ) return null;
if (typeof(el.type)!=typeof(underfined)){
	var etype=el.type.toUpperCase();
	if (etype=="SELECT-ONE") return Html.SELECT;
	return etype;
}
if (typeof(el.tagName)!=typeof(underfined)){
  return el.tagName.toUpperCase();
}
 if ( typeof(el.length)!=typeof(underfined) && typeof(el[0].type)!=typeof(underfined)) {
	 return el[0].type.toUpperCase();
 }
 return null;
}


Html.getElementVal=function(el){
    var etp=Html.checkElement(el);
	var str=null;
    if (etp==Html.SELECT){
		  str=SelectTag.seletedValue(el);
	}else if (etp==Html.RADIO){
	 	 str=Html.getSelectedRadioValue(el);
    }else {
	   str=el.value;
    } 
  return str;
}

Html.getSelectedRadio=function (buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
     return -1;
} 


Html.getSelectedRadioValue=function(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = Html.getSelectedRadio(buttonGroup);
   if (i == -1 ) {
      return null;
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} 


Html.removeSpecial=function(s)
{
	s = s.replace(/\\/g, '\\\\');
	s = s.replace(/\r\n|\r/g, '');
	s = s.replace(/\'/g, '\\\'');
	s = s.replace(/\"/g, '\\\"');
	s = s.replace(/\n/g, '');

	//  str=str.replace(/>/gi,"&gt;");
	//  str=str.replace(/</gi,"&lt;");
  return s;
}

Html.addSpecial=function(s)
{
 s = s.replace(/\\\'/g, '\'');
 s = s.replace(/\\\"/g, '\"');
 s = s.replace(/\\\\/g, '\\');
 return s;
}

Html.removeQuot=function(s){
	s = s.replace(/\"/g, '&quot;');
	return s;
}

// Is CheckBox checked
Html.isChecked=function(el){
  if ( el.checked == '') return false;
  return true;
}

//----  Input ----------------------------
InputTag.prototype = new HtmlTag;
InputTag.prototype.constructor = InputTag;
InputTag.superclass = HtmlTag.prototype;

function InputTag(name,typeTag,value){
  if ( arguments.length == 3 ){
	 this.init("INPUT");
	 this.add("name",name);
	 this.add("type",typeTag);
     this.add("value",value);
   }else {
      alert("InputTag:InputTag");
   }
}

//----  Select  ----------------------------
// name - 

SelectTag.prototype = new HtmlTag;
SelectTag.prototype.constructor = SelectTag;
SelectTag.superclass = HtmlTag.prototype;

function SelectTag(name,vals,names){
  if ( arguments.length == 3 )
   {
	this.init(Html.SELECT);
	this.add("name",name); 
	if (vals!=null){
	    for (var i=0;i<vals.length;i++){
	      var o = new HtmlTag(Html.OPTION);
	      o.add("value",vals[i]);
	      o.addString(names[i]); 
	      this.addTags(o);
	    } 
	}
       
   }else {
      alert("Error:SelectTag");
   }
}
//------------------------------------------
// Return Value of Select in index='ind'
SelectTag.prototype.getValue = function (ind)
{
  return this.getTags()[ind].get("value");
}

SelectTag.prototype.removeOptionByIndex = function (ind)
{
  var par = this.getParent();
  if (par!=null)  
  {
	//- No Structure treatment
	SelectTag.removeOptionByIndex(
		document[par.get("name")].elements[this.get("name")],ind);
  }
  else
   alert("Warning:cant remove option1");
}

SelectTag.prototype.addOption = function (value,text)
{
   var par = this.getParent();
   var o = new HtmlTag(Html.OPTION);
   o.add("value",value);
   o.addString(text); 

   this.addTags(o);
   if (par!=null && document[par.get("name")].elements[this.get("name")])
	 {
	     var sel = document[par.get("name")].elements[this.get("name")];
	     SelectTag.addOption(sel,value, text);
	 }
   return o;
}


SelectTag.removeOptionByValue = function(sel,val){
 for (var i=0;i<sel.options.length;i++)
  if (sel.options[i].value==val)
    sel.options[i]=null;
}

SelectTag.selectOptionByValue = function(sel,val){
 for (var i=0;i<sel.options.length;i++)
  if (sel.options[i].value==val){
	    SelectTag.setSelectedIndex(sel,i);
		return;
	}
}

SelectTag.setSelectedIndex= function(sel,val){
 sel.selectedIndex=val;
}

SelectTag.removeSelectedOption = function(sel){
 if (sel.selectedIndex>=0)
	sel.options[sel.selectedIndex]=null;
}

SelectTag.removeOptionByIndex = function(sel,ind){
  if (ind>=0&&ind<sel.options.length){
		sel.options[ind]=null;
	}
}
SelectTag.removeAllOptions= function(sel){
 while (sel.options.length>0)
    sel.options[0]=null;
}

SelectTag.addOption = function(sel,name,text){
	sel.options[sel.options.length]=new Option(name,text);
}

SelectTag.seletedValue=function(sel){
	return sel.options[sel.selectedIndex].value;
}
//------------  Form Tag  --------------------

FormTag.prototype = new HtmlTag;
FormTag.prototype.constructor = FormTag;
FormTag.superclass = HtmlTag.prototype;

function FormTag(name){
  if ( arguments.length == 1 ){
	  this.init(Html.FORM);
	  this.add("name",name);
   }else{
      alert("Error:FormTag");
   }
}

FormTag.prototype.submit = function(){
  document[this.get("name")].submit();
  return true;
}
 

//------------ UTF8 String  --------------------

function UTF8String(str){
 this.tag=Html.UTF8STRING;
 this.text=str;
 this.parent=null;
}
UTF8String.prototype.show = function(){
 return this.text;
}
UTF8String.prototype.type=function(){
  return this.tag;
}

UTF8String.prototype.setParent = function (parent){
 this.parent=parent;
}
UTF8String.prototype.getParent = function (){
 return this.parent;
}
 
//------------ GENERAL tag  --------------------


function HtmlTag(tag){
if ( arguments.length == 1 )
    this.init(arguments[0]);
 
}
 

HtmlTag.prototype.init = function(id){
  this.tag=id;
  this.altOptions=new StringHash();
  this.arrFileds = new Array(0);
  this.parent = null;
}


HtmlTag.prototype.write=function(){
 document.write( this.show() );
}

HtmlTag.prototype.show=function(){
 
  var str='<'+this.tag;
  var i=0;
  var val=this.altOptions.getByIndex(i);
  while (val!=null) {
		str+=' '+val[0]+'="'+val[1]+'"';
        i++; 
	    val=this.altOptions.getByIndex(i);
  } 
  str+='>';
 
  for (var i=0;i<this.arrFileds.length;i++)
	{
	   str+=this.arrFileds[i].show();
	}
  
  str+='</'+this.tag+'>';
//  alert(this.tag+":"+str);
  return str;
}
 

HtmlTag.prototype.type = function (){
 return this.tag;
}

HtmlTag.prototype.getParent = function (){
 return this.parent;
}
HtmlTag.prototype.setParent = function (parent){
 this.parent=parent;
}


HtmlTag.prototype.add = function (){
 for (var i = 0; i < arguments.length; i+=2) 
   this.altOptions.add(arguments[i],arguments[i+1]);
}
 
HtmlTag.prototype.get = function (name){
 return this.altOptions.get(name);
}

HtmlTag.prototype.set = function (name,val){
  this.altOptions.add(name,val);
}

HtmlTag.prototype.getTags = function ()
{
  return this.arrFileds;
}

HtmlTag.prototype.addTags = function (){

 for (var i = 0; i < arguments.length; i++)
 {
  this.arrFileds[this.arrFileds.length]=arguments[i]; 
  arguments[i].setParent(this);
 }
}

HtmlTag.prototype.addString = function (str){
  this.arrFileds[this.arrFileds.length]=new UTF8String(str); 
}


function Product(id,price,weight,name,pictures,quantity,multiprop,code,sortorder,filename,downloadnum){ 
  this.arr = new Array(0);
  this.arr['id']=id;
  this.arr['price']=price;
  this.arr['weight']=weight;
  this.arr['name']=name;
  this.arr['pictures']=pictures;
  this.arr['quantity']=quantity;
  this.arr['multiprop']=multiprop;
  this.arr['code']=code;
  this.arr['sortorder']=sortorder;
  this.arr['filename']=filename;
  this.arr['downloadnum']=downloadnum;
}
 Product.PRODUCT_LIST=new List();
 Product.CookieSize=3500;
 Product.CookieName="!PR!";
 Product.number=0;
 Product.VisDel="-";
 Product.showDel=";";
 
 Product.getList= function (){ 
	 return Product.PRODUCT_LIST;
 }
 Product.addToList=function (prod){ 
	 return Product.PRODUCT_LIST.add(prod);
 }
 // returns real number returned by queary
 Product.getRealListSize = function(){	
	return Product.number;
 }
 Product.setRealListSize = function(num){	
	Product.number=num;
 }

//-------------------------------------------------------
// Return Product By ID, real id
//-------------------------------------------------------
Product.getById= function (Id){
	 var pr;
	 for (var i=0;i<(Product.getList()).size();i++){
		pr=(Product.getList()).get(i);
		if (Id==pr.getId()) return pr;
	 }
	 return null;
}

Product.convertPropToId= function (Id,prop){
 if (typeof(prop)== typeof(underfined)) prop="";
 var list=new List();
 list.add(Id,prop);
 return list.convertToStr();
}

Product.convertMixToArr= function (val){
  return (List.convertToList(val)).toArray();
}

Product.getRealId= function (fakeId){
 var arrm=Product.convertMixToArr(fakeId);
 return arrm[0];
}

Product.getCombinedProp= function (fakeId){
 //arrm[0] - realID, arrm[1] - hash of properties
  var arrm=Product.convertMixToArr(fakeId);
  return arrm[1];
}



//-------------------------------------------------------
// Add product to cart
//-------------------------------------------------------
Product.addToCartProp = function (Id,count,prop){

  var fakeId=Product.convertPropToId(Id,prop);	
  var n = Product.countInCart(fakeId);
  if (typeof(count)== typeof(underfined)) count=1;
  n+=count;
  return Product.setCountGeneral(Id,fakeId,n);
}
//-------------------------------------------------------
// Set count prop
//-------------------------------------------------------
Product.setToCartProp = function (Id,count,prop){
  var fakeId=Product.convertPropToId(Id,prop);	
  return Product.setCountGeneral(Id,fakeId,count);
}
//-------------------------------------------------------
// Remove all products
//-------------------------------------------------------
Product.removeAllFromCart = function (){
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);
  prodCookies.removeAll();
  prodCookies=null;
}

//-------------------------------------------------------
// Count products in cart
//-------------------------------------------------------
Product.countInCartAll = function (){
	 var sum=0;
	 var ids=Product.getIdsFromCart();
	 for (var i=0;i<ids.length;i++)
		sum+=Product.countInCart(ids[i]);
     return sum; 
 }
//-------------------------------------------------------
// Count products in cart real ids eq "ID"
//-------------------------------------------------------
Product.countInCartAllId = function (realId){
	 var sum=0;
	 var ids=Product.getIdsFromCart();
	 for (var i=0;i<ids.length;i++){
       if (Product.getRealId(ids[i])==realId)
        	sum+=Product.countInCart(ids[i]);
	 }
     return sum; 
 }
//-------------------------------------------------------
// return number products in cart
//-------------------------------------------------------
Product.countInCart = function (fakeId){
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);
  var val = prodCookies.get( fakeId );
  var n=0;
  if (val!=null)
	  n=Number(val);
  prodCookies=null;
  return n;
}

Product.removeFromCart = function (fakeId){
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);
  prodCookies.remove(fakeId);
  prodCookies=null;
}

Product.setCountGeneral = function (Id,fakeId,n){
   return  Product.setCountGeneralRet(Id,fakeId,n)==n;
}

Product.setCountGeneralRet = function(Id,fakeId,n){
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);
  var pr = Product.getById(Id);
  if ( !prodCookies.set(fakeId,n) )  //!!!
	alert(Visual.unexpectedError);

  var totalQ=Product.countInCartAllId(Id);
  if (pr.getQuantity()<totalQ && Project.enableQCount){
 	alert(Visual.outOfStock);
	n=n-(totalQ-pr.getQuantity());
	if (n==0){
		prodCookies.remove(fakeId);
	}else{
		if ( !prodCookies.set(fakeId,n) ) 
			alert(Visual.unexpectedError);
	}
  }
	
  prodCookies=null;
  return n;
}


//-------------------------------------------------------
// Return Product IDS Array from Cart
//-------------------------------------------------------
Product.getIdsFromCart= function(){
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);
  var item=0;
  var pair = prodCookies.getByIndex(item++);
  var ids= new Array(0); 
  while (pair!=null){
	  ids[ids.length]=pair[0];
	  pair = prodCookies.getByIndex(item++);
  }
  prodCookies=null;
  return ids;
}

//-------------------------------------------------------
// Need recheck
//-------------------------------------------------------
Product.getNumProductsInCart= function(){
  var arr=Product.getIdsFromCart();
  return arr.length;
}

// alg: if SP_QUOTE found return -1;
// 
Product.prototype.getPriceForCart=function(qnt,fakeID){
	if ( this.getMultipropVal(Charge.SP_QUOTE) != null ) return -1; //quote, the product price have to be 0 in DB
	var j=0;
	var qval=this.getMultipropVal(Charge.SP_QNT);
	var priceFound=false;
	var price=0;
	if (qval!=null ){
		  var mhash	= new StringHash(qval);
		  var i = 0;
		  var arr1 = mhash.getByIndex(i);
		  var arr_val=new Array(0);
		  do{
			arr_val[arr_val.length]=arr1[0];
			i++;
			arr1 = mhash.getByIndex(i);
		  }while (arr1!=null);

		  arr_val.sort(Project.sortNumber);
		  for (i=0;i<arr_val.length;i++)
			if (qnt<=arr_val[i] || i==(arr_val.length-1)){
				price=this.applyQntCharge(new StringHash( mhash.get(arr_val[i]) )); 
				priceFound=true;
				break;
			}
	 }else{
		 price=this.getPrice();
	 }
	 		
	 price+=this.getAddPrice(fakeID,this);
	 return qnt*price;
}

//return price
Product.prototype.applyQntCharge=function(chargeHash){
	var charge= new Charge();
	charge.initFromHash(chargeHash);
	return Number(charge.get('cost1'))*Project.mconvert;
}


// return total amount of additional prices
Product.prototype.getAddPrice=function (fakeId,pr){ // get product also for performance
 
  var arrm=Product.convertMixToArr(fakeId);
  if (!StringHash.validate(arrm[1])) return 0; // prev to ver. 1.32
  var h=new StringHash(arrm[1]);
  var j=0;
  var sum=0;
  var arr = h.getByIndex(j++);	
  var ind=0;
  while (arr!=null ) {
	 
	  if (Charge.isSpecial(arr[0])){
		  var strh=pr.getMultipropVal(arr[0]);
		  var h1=new StringHash( strh );
		  if (Charge.isSP_ADDPRICE(arr[0])) {
			  sum+=Number(h1.getByIndex(arr[1])[1]);
		  }else if ( Charge.isSP_CHECKBOXPRICE(arr[0]) ){
			  		sum+=Number(h1.get("2"));
	   			}else
	   			  alert("error unknown special");
		    		  
	  }
	  arr =h.getByIndex(j++);
	  ind++;	
  }
  return sum*Project.mconvert;
}


// return visual part from ID
Product.getVisualProp= function (fakeId){

  var arrm=Product.convertMixToArr(fakeId);
  var pr=null;
  //if (!StringHash.validate(arrm[1])) return arrm[1]; // prev to ver. 1.32
  var h=new StringHash(arrm[1]);
  
  var strArr=Array(0);	
  var j=0;
  var arr = h.getByIndex(j++);	
  var ind=0;
  while (arr!=null ) {
	  
	  if (!Charge.isSpecial(arr[0])) { 
		  strArr[strArr.length]=arr[1];
	  }else{
		  if (pr==null) pr = Product.getById(arrm[0]);
		  var strh=pr.getMultipropVal(arr[0]);
		  var h1=new StringHash( strh );
		  
		  if (Charge.isSP_ADDPRICE(arr[0])) {
			  strArr[strArr.length]=MultiLang.get(h1.getByIndex(arr[1])[0]);
		  }else if ( Charge.isSP_CHECKBOXPRICE(arr[0]) ){
			  		strArr[strArr.length]=MultiLang.get(h1.get("1"));
	   			}else
	   			  alert("error unknown special");
		  
		  						 
		  
	  }
	  ind++;
	  arr =h.getByIndex(j++);	
  }

  return strArr;
}


Product.prototype.getMultipropVal= function (name){
 var j=0;
 var arr = (this.getMultiProp()).getByIndex(j);	
 while (arr!=null ) {
   var namev=MultiLang.get(arr[0]);
   if (namev==name) return MultiLang.get(arr[1]);
   j++;
   arr = (this.getMultiProp()).getByIndex(j);	
 } 
  return null;
}

// Return value
Product.prototype.get = function (name){
  return this.arr[name];
}
// Set value
Product.prototype.set = function (name,value){
  this.arr[name]=value;
}


// Return error string,if product not valid,empty string overwise
Product.prototype.valid = function (){
  var err="";
  if (isNaN(this.getPrice()) )
	  err="Error in price format:"+this.getPrice();
  return err;
}

Product.prototype.initForm=function (form)
{
  for (var prop in this.arr){
//	str+=prop+":"+this.arr[prop];
	if (form.elements[prop]!=null)
	  form.elements[prop].value=this.arr[prop];
	else
	  alert("Product.js Error,cant init:"+prop);
  }
 
}

Product.prototype.setName = function (name){
  this.set('name',name);
}
Product.prototype.getName = function (){
  return this.get('name');
}

Product.prototype.setCode = function (name){
  this.set('code',name);
}
Product.prototype.getCode = function (){
  return this.get('code');
}

Product.prototype.getId = function (){
  return this.get('id');
}

Product.prototype.getMultiProp = function (){
  return this.get('multiprop');
}
Product.prototype.setMultiProp = function (val){
  this.set('multiprop',val);
}

Product.prototype.getQuantity = function (){
  return this.get('quantity');
}
Product.prototype.setQuantity = function (quant){
  this.set('quantity',quant);
}

Product.prototype.getPrice = function (){
  return Number(this.get('price'));
}
Product.prototype.setPrice = function (price){
  this.set('price',price);
}
Product.prototype.getWeight = function (){
  return Number(this.get('weight'));
}
Product.prototype.setWeight = function (weight){
  this.set('weight',weight);
}
Product.prototype.getSortOrder = function (){
  return Number(this.get('sortorder'));
}
Product.prototype.setSortOrder = function (val){
  this.set('sortorder',sortorder);
}

Product.prototype.getPicture = function (){
  return this.get('pictures');
}
Product.prototype.setPicture = function (picture){
  return this.set('pictures',picture);
}

Product.prototype.toString = function (){
 return "id="+this.getId()+"&name="+this.getName()+"&price="+this.getPrice(); 
}

/* Return product list,ids: Array of ids
Product.getListFromIdArray= function(ids){
 return getProductList(new Filter(new RegExp("^id=("+ids.join("|")+")&","i")));
}*/

// return hash {"VisDel",Visual prop}{spid,val}...
// where spid is name of special property
Product.getProductProperties= function(id){
  
  if (typeof(document.forms['formfullProduct'+id].elements)==typeof(undefined)) return "";

  var i=0;
  var ret=new StringHash();
  var radio=new StringHash();
  var ind=0;
  var form=document.forms['formfullProduct'+id];
  for (var i=0;i<form.elements.length;i++){
    
	var el=form.elements[i];
    var etp=Html.checkElement(el);
	if (etp==Html.SELECT){
			
		   if ( Charge.isSpecial(el.name) ){
			  ret.add(el.name,el.selectedIndex);
		   }else{	
			  var str=SelectTag.seletedValue(el);
			  if (ind>0)str=Product.showDel+str;
			  ret.add(Product.VisDel+ind,str);
		   }
		ind++;
	}else if (etp==Html.RADIO){
	  if (radio.get(el.name)==null){
	 	 var str=Html.getSelectedRadioValue(el);
	  	 if (str!=null){
		  	 radio.add(el.name,"");
			 if (ind>0)str=Product.showDel+str;
  	     	 ret.add(Product.VisDel+ind,str);
	     	ind++;
         }
     }
    }else if (etp==Html.TEXT ){
	  var str=el.value;
	  if (ind>0)str=Product.showDel+str;
	   ret.add(Product.VisDel+ind,str);
	   ind++;
    }else if (etp==Html.CHECKBOX){
	        if (Html.isChecked(el)){
		 		if ( Charge.isSpecial(el.name) ){
				  ret.add(el.name,"0");
		   		}else{	
			  		var str=el.value;
			  		if (ind>0)str=Product.showDel+str;
			  		ret.add(Product.VisDel+ind,str);
		   		}
	  			ind++;		   
  			}
   	 } 
  }
  return ret.toString();
}

Product.refreshProdPrice= function(){
    
	var pr=(Product.getList()).get(0);
    var fakeId=Product.convertPropToId(pr.getId(),Product.getProductProperties(pr.getId()));	
    var sum=pr.getPriceForCart(1,fakeId);
    var el=Html.getElement("productprice_id");
    el.innerHTML=sum;	
}﻿

function Category(id,parent,name,status,picture){ 
  this.arr = new Array();
  this.arr['id']=id;
  this.arr['parent']=parent;
  this.arr['name']=name;
  this.arr['status']=status;
  this.arr['picture']=picture;
}

Category.urlName="catid";
Category.CATEGORIES_LIST=new List();
Category.PRODUCT_CAT_LIST=new Array(0);
Category.PAGE_CAT_LIST=new Array(0);

Category.CAT_IND_CACHE=new Array();//catID->CATEGORIES_LIST index
Category.PARENT_IND_CACHE=new Array(); //CatId->Array[catid1,catid2,..]

Category.getList= function (){ 
	 return Category.CATEGORIES_LIST;
 }
 
Category.addToList=function (cat){ 
	 Category.CATEGORIES_LIST.add(cat);
	 
	 Category.CAT_IND_CACHE[cat.getId()]=Category.CATEGORIES_LIST.size()-1;
	 var parentId=cat.getParent();
	 if ( ! Category.PARENT_IND_CACHE[ parentId ] )   Category.PARENT_IND_CACHE[ parentId ] = new Array(0);
	 var parentLen= Category.PARENT_IND_CACHE[ parentId ].length; 
	 Category.PARENT_IND_CACHE[ parentId ][parentLen] = cat.getId();
 }

 Category.addPageToList=function (name,val){ 
	if (typeof(Category.PRODUCT_CAT_LIST[name])==typeof(undefined))
		 Category.PAGE_CAT_LIST[name]=val;
	else
		 Category.PAGE_CAT_LIST[name]=Category.PAGE_CAT_LIST[name].concat(val);
}
Category.getPageList= function (){ 
	 return Category.PAGE_CAT_LIST;
 }

Category.getPCList= function (){ 
	 return Category.PRODUCT_CAT_LIST;
 }
Category.addPCToList=function (name,val){ 
	if (typeof(Category.PRODUCT_CAT_LIST[name])==typeof(undefined))
		 Category.PRODUCT_CAT_LIST[name]=val;
	else
		 Category.PRODUCT_CAT_LIST[name]=Category.PRODUCT_CAT_LIST[name].concat(val);
 }


Category.prototype.getPicture = function (){
  return this.arr['picture'];
}
Category.prototype.setPicture = function (name){
  this.arr['picture']=name;
}

Category.prototype.getName = function (){
  return this.arr['name'];
}
Category.prototype.setName = function (name){
  this.arr['name']=name;
}

Category.prototype.getId = function (){
  return this.arr['id'];
}

Category.prototype.getParent = function (){
  return this.arr['parent'];
}
Category.prototype.setParent = function (parent){
  this.arr['parent']=parent;
}

Category.prototype.getStatus = function (){
  return this.arr['status'];
}
Category.prototype.setStatus = function (status){
  this.arr['status']=status;
}

Category.prototype.toString = function (){
 var ret="id="+this.getId();
 ret+="&parentid="+this.getParent();
 ret+= "&name="+this.getName();
 return ret;
}

//-----------------------------------
Category.getCategoryByID =  function (idc){
   /*for (var i=0;i<Category.CATEGORIES_LIST.size();i++){
		var c = Category.CATEGORIES_LIST.get(i);
		if (c.getId()==idc) return c;
	 }*/
	 
	 return Category.CATEGORIES_LIST.get ( Category.CAT_IND_CACHE[ idc ] );
	
 }
//-----------------------------------
Category.getByStatus =  function (statusArray){
   var list = new List();
   for (var i=0;i<Category.CATEGORIES_LIST.size();i++){
		var c = Category.CATEGORIES_LIST.get(i);
		if (existInArray( statusArray, c.getStatus() ) ) { list.add(c); }
	 }
	return list;
 }

// Return direct children list 
Category.getChildrenByStatus =  function (idc,statusArray){
   /*var list = new List();
   for (var i=0;i<Category.CATEGORIES_LIST.size();i++){
		var c = Category.CATEGORIES_LIST.get(i);
		if (c.getParent()==idc && existInArray( statusArray, c.getStatus() ) )	list.add(c);
	 }
   return list;*/
   var list = new List();
 
   if (!Category.PARENT_IND_CACHE[ idc ]) return list;
   for (var i=0;i<Category.PARENT_IND_CACHE[ idc ].length;i++){
  	 var c1 = Category.getCategoryByID( Category.PARENT_IND_CACHE[ idc ][i]  ); 
  	 if ( existInArray( statusArray, c1.getStatus() ) )  list.add(c1);
   }
 
   return list;
   
   
 }

// Return direct children list 
Category.getChildren =  function (idc){
   var list = new List();
 
   if (!Category.PARENT_IND_CACHE[ idc ]) return list;
   for (var i=0;i<Category.PARENT_IND_CACHE[ idc ].length;i++){
  	 var c1 = Category.getCategoryByID( Category.PARENT_IND_CACHE[ idc ][i]  ); 
  	 list.add(c1);
   }
 
   return list;
 }

// Return total children list 
Category.getAllChildren =  function (idc){
   var list = new List();
   for (var i=0;i<Category.CATEGORIES_LIST.size();i++){
		var c = Category.CATEGORIES_LIST.get(i);
		if ( Category.isFather(c.getId(),idc ) ) {
				list.add(c);
		}
	 }
   
   return list;
}
  
//-----------------------------------------------------------
// return true if id is descendant of f_id
Category.isFather =  function (id,f_id){
    var cat =  Category.getCategoryByID(id);
	while (cat!=null && cat.getParent()!=f_id ){
		cat = Category.getCategoryByID( cat.getParent() );
	}
	if (cat!=null) return true;
	return false;
 }
//-----------------------------------------------------------
// Return array of Categoris from "fromID" to "toId"
Category.getPath =  function (fromId,toId)
{
	var arr=new Array(0);
	var cat=Category.getCategoryByID(toId); 
	if (cat!=null){
		arr[arr.length]=cat; 
		cat =  Category.getCategoryByID(cat.getParent());
	}
	while (cat!=null){
	 arr[arr.length]=cat; 
     cat =  Category.getCategoryByID(cat.getParent());
	}
    arr=arr.reverse();
	return arr;
}

Category.current=function(){
  var catid = Url.getCurrentValue(Category.urlName);
   if (catid==null)catid=-1;
    else  catid=Number(catid);
  return catid;
 }

function getProductCategories(id,isByProduct){
  return getItemsCategories(id,isByProduct,Category.PRODUCT_CAT_LIST);
}

function getPageCategories(id,isByProduct){
  return getItemsCategories(id,isByProduct,Category.PAGE_CAT_LIST);
}

// in:  product_id or category_id ,isByProduct (true - id is productId else category ID) 
// out: array of category ids or products ids according by isByProduct
function getItemsCategories(id,isByProduct,list){
 var ret=new Array(0);
 //var arr=Category.PRODUCT_CAT_LIST;
 if (isByProduct) {	 
    if (list[id]) return list[id]; 
 }else{  
	for (var prop in Category.PRODUCT_CAT_LIST)
		if ( existInArray(list[prop],id) ) ret[ret.length]=prop;
 }	  
 return ret;
}
﻿
function Novigation(){
}
Novigation.fName="nov_form";
Novigation.send_method=true;// False with URL, True with Form Post
Novigation.secureCart=false; // True = secure checkout
Novigation.forceThisForm=false; // True to force Novigation Form
//4- reserved for outside thankyou page
Novigation.PAGE_FRAME="3";
Novigation.PAGE_START="0";
Novigation.PAGE_CART="1";
Novigation.PAGE_THX="2";
Novigation.PAGE_XML="5";
Novigation.currPage=Novigation.PAGE_START;

//------------------------------------
Novigation.integrate = function(page){
	var str;
	str="<html><head></head><body>";
	str+=Integrate.getForm(Project.Integrate).show();
	str+="<script language='javascript'>document.forms['"+Integrate.fName+"'].submit();</script>";
	str+="</body></html>";
	document.write(str);

}
//------------------------------------

Novigation.getForm = function(fname,prid,page){

  var form= new FormTag(fname);
  form.add("method","post");
  form.add("action",Url.getCurrentLocation()+"index.php");
  var f1 = new InputTag("pids",Html.HIDDEN,prid);// Ids of products for view
  var f2 = new InputTag("count",Html.HIDDEN,"");// Count of products
  var f3 = new InputTag("cpage",Html.HIDDEN,page);// Current Page number
  var f4 = new InputTag("prophash",Html.HIDDEN,"");// 
  form.addTags(f1,f2,f3,f4);
  return form;
}

//------------------------------------
Novigation.fillFormForCheckOut= function(form,page){
	var mids=Product.getIdsFromCart();
	var counts="";
	var ids="";
	var prophash=new StringHash();
	for (var i=0;i<mids.length;i++){
		//var arrm=Product.convertMixToArr(mids[i]);
		if (ids!="") { ids+=","; counts+=","; }
		ids+=Product.getRealId(mids[i]);
		counts+=Product.countInCart(mids[i]);
		prophash.add( i,Product.getCombinedProp(mids[i]) );
		
	 }

	 if (ids=="") {
		 alert(Visual.strNoProd);
		 if (Novigation.currPage==Novigation.PAGE_CART)
		 	 Url.go("http://"+Url.removeProtocol(Url.curLoc()) ) ;
		 return false;
	 }
		
	 form.elements['cpage'].value=page;
	 form.elements['count'].value=counts;
	 form.elements['pids'].value=ids;
	 form.elements['prophash'].value=prophash.toString();
	
	 return true;
}


Novigation.moveTo= function(page){

   var url="#";
   switch (page){
	case Novigation.PAGE_START: 
		url=Url.getCurrentLocation()+"index.php?"+Url.getQueary(Url.curLoc());	
		url=Url.setProtocol(url,"http://");
		return url;
	break;
	case Novigation.PAGE_CART: 
	   if (Project.Integrate!=Integrate.NOINTEGRATION &&  Integrate.isDirect(Project.Integrate) ){
		 Novigation.integrate(page);
	     return url;
	   }
	   if (Novigation.currPage==Novigation.PAGE_CART)
		   	var form=document.forms["fcheckout"];
	   else{
		form=document.forms[Novigation.fName];
	   }
	   form.action=Url.getCurrentLocation()+"index.php?"+Url.getQueary(Url.curLoc());	
	   if (Novigation.secureCart) form.action=Url.setProtocol(form.action,"https://");	
  
	   form.action=Url.delURLvalue(form.action,"cpage");	
	   form.action=Url.delURLvalue(form.action,"pids");
	   if (!Novigation.fillFormForCheckOut(form,page)) 
			return;
	   form.submit();

   	break;	

	case Novigation.PAGE_THX: 

		var form=document.forms["fcheckout"];
		form.action=Url.getCurrentLocation()+"index.php";
		if (!Novigation.fillFormForCheckOut(form,page)) 
			return;
		form.submit();
	break;

}

  if(!Novigation.send_method)//GET
	  return url;

}
//------------------------------------

Novigation.goToCategory = function(id){
 Url.go("/index.php?catid="+id);
}

Novigation.goToManufacture= function(id){
  var str="/index.php?catid1="+id;
  var cat=Url.getCurrentValue("catid");
  if (cat!=null) str+="&catid="+cat;
  Url.go(str);
}

Novigation.fixSelectValues= function(){

if (document.srchform && Html.checkElement(document.srchform.elements['sby'])==Html.SELECT)
	SelectTag.selectOptionByValue(document.srchform.elements['sby'],Url.getCurrentValue('sby'));

var el=Html.getElement('catid1');		
if ( el!=null && Html.checkElement(el)==Html.SELECT ){
	SelectTag.selectOptionByValue(el,Url.getCurrentValue('catid1'));
 }
}

Novigation.crateSearchUrl = function(form){
 if (isNaN(form.elements['minprice'].value) ||isNaN(form.elements['maxprice'].value) ){
	  alert(Visual.mustBeNumber);
	  return false;
  }
  if (isNaN(form.elements['catid'].value) ){ alert("Wrong category"); return false; }
  
  var url = "/index.php?";
  url = Url.setURLvalue(url,"srch",form.elements['srch'].value);
  url = Url.setURLvalue(url,"minprice",form.elements['minprice'].value);
  url = Url.setURLvalue(url,"maxprice",form.elements['maxprice'].value);
  url = Url.setURLvalue(url,"catid",form.elements['catid'].value);
  url = Url.setURLvalue(url,"cpage",Novigation.PAGE_START);
  url = Url.setURLvalue(url,"page",0);
  url = Url.setURLvalue(url,"sby",form.elements['sby'].value);
  return url;	
}

Novigation.search = function(form){
  var url = Novigation.crateSearchUrl(form);
  if (url!=false) Url.go(url);
   else  return false;
  return true;
}


//----------------------------------------
//  Search products by query
Novigation.searchIfEnter = function(event,form){
  if (!Project.checkEnter(event)) return true;
  Novigation.search(form);
  return false;
}


Novigation.toCheckOut = function(isGo){
   if(isGo && confirm(Visual.strProdMes[0]))
	  Novigation.moveTo(Novigation.PAGE_CART); 
   else
    if (typeof(Visual.showCartContentMess) != typeof(undefined)) 
	   Visual.showCartContentMess();

}

Novigation.writeForm = function(){
  	Novigation.getForm(Novigation.fName,"","","").write();
}

Novigation.fillReslts=function(mess){
AutoComplete.resetResults();
var xmlobject=Dom.loadXML(mess);
 try{
	var res = xmlobject.getElementsByTagName('Result');
	for (var i=0; i < res.length; i++){
    	AutoComplete.addResult(res[i].childNodes.item(0).data);
	 }
  }catch(err){
	   alert("Error:"+mess+":"+err.description);
  }
  AutoComplete.setContent();	
}

Novigation.getSearchData= function(form){
   if (form.elements['srch'].value.length<3) return;
   var url = Novigation.crateSearchUrl(form);
  if (url==false) return;
  url = Url.setURLvalue(url,"cpage",Novigation.PAGE_XML);
  url = Url.setURLvalue(url,"srch",encodeURIComponent(form.elements['srch'].value));
  ajaxObj = new XMLHttp(true);
  ajaxObj.get(url,Novigation.fillReslts);	

}﻿
function Integrate(){
}

Integrate.fName="fintegrate";
Integrate.NOINTEGRATION=0;
Integrate.MALS=1;
Integrate.GOOGLE_L1=2;
//Integrate.MALS_PARAM=Array("http://ww7.aitsafe.com/cf/addmulti.cfm","91105341");
//Integrate.GOOGLE_L1_PARAM=Array("864656326630388","qMj9TiMAduwjUZ1ugnb2Wg");
 

Integrate.isDirect = function(type){
  switch ( type ) {
	case Integrate.MALS: 
	  return true;
	  break;
	case Integrate.GOOGLE_L1: 
	  return false;
	  break;
  }
  return false;
}

Integrate.getButtonStr = function(type){
  var str="";	
  /*switch ( type ) {
	case Integrate.GOOGLE_L1: 
	  str='<input type="image" name="Google Checkout" alt="Fast checkout through Google" src="http://checkout.google.com/buttons/checkout.gif?w=180&h=46&style=white&variant=text&loc=en_US" onclick="Novigation.integrate('+type+')" height="46" width="180"/>';
	  break;
  }*/
  return str;
}


Integrate.getForm = function(type){
  var fname=Integrate.fName; 
  var prodCookies = new DummyCookies(Product.CookieName,Product.CookieSize);

  switch ( type )
  {
	case Integrate.MALS: 
	  var form = new FormTag(fname);
	  form.add("action",Integrate.MALS_PARAM[0]);
	  form.add("method","post");
	  form.addTags( new InputTag("userid",Html.HIDDEN,
				Integrate.MALS_PARAM[1]));
	  form.addTags( new InputTag("return",Html.HIDDEN,
			  Url.removeProtocol(location.href) ));
			
	  var ids=Product.getIdsFromCart();
	  for (var i=0;i<ids.length;i++){
		var nInCart=Product.countInCart(ids[i]);
		var pr=Product.getById( Product.getRealId(ids[i]) );
		form.addTags( new InputTag("qty"+(i+1),Html.HIDDEN,nInCart));
		var n=Html.removeQuot(Visual.formatStr(pr.getName()))+"(Id:"+pr.getId()+Product.getVisualProp(ids[i])+")";
		form.addTags( new InputTag("product"+(i+1),Html.HIDDEN,n) );
	  	form.addTags( new InputTag("price"+(i+1),Html.HIDDEN,pr.getPriceForCart(nInCart,ids[i]) ) );
	  }	
	  Product.removeAllFromCart();
	  return form;
	  break;
  
  /*	case Integrate.GOOGLE_L1: 
	  var form = new FormTag(fname);
	  form.add("action","https://sandbox.google.com/checkout/cws/v2/Merchant/"+Integrate.GOOGLE_L1_PARAM[0]+"/checkoutForm");
	  form.add("method","post");
	  form.add("accept-charset","utf-8");

	  form.addTags( new InputTag("_charset_",Html.HIDDEN,""));
	  form.addTags( new InputTag("return",Html.HIDDEN, Url.removeProtocol(location.href) ));
	  if (ShoppingCart.getShipping()!=0){
		  form.addTags( new InputTag("ship_method_name_1",Html.HIDDEN,"Shipping"));
		  form.addTags( new InputTag("ship_method_price_1",Html.HIDDEN,ShoppingCart.getShipping()));
	  }
				
	  var ids=Product.getIdsFromCart();
	  for (var i=0;i<ids.length;i++){
		var nInCart=Product.countInCart(ids[i]);
		var arrm=Product.convertMixToArr(ids[i]);
		var pr=Product.getById(arrm[0]);
		form.addTags( new InputTag("item_quantity_"+(i+1),Html.HIDDEN,nInCart));
		var n=Html.removeQuot(Visual.formatStr(pr.getName()))+"(Id:"+pr.getId()+arrm[1]+")";
		form.addTags( new InputTag("item_name_"+(i+1),Html.HIDDEN,n) );
		form.addTags( new InputTag("item_description_"+(i+1),Html.HIDDEN,"") );
	  	form.addTags( new InputTag("item_price_"+(i+1),Html.HIDDEN,pr.getPriceForCart(nInCart) ) );
	  }	

	  if (ShoppingCart.getOtherCharges()!=0){
		form.addTags( new InputTag("item_name_"+(i+1),Html.HIDDEN,"Other charges") );
		form.addTags( new InputTag("item_description_"+(i+1),Html.HIDDEN,"") );
	  	form.addTags( new InputTag("item_price_"+(i+1),Html.HIDDEN,ShoppingCart.getOtherCharges()));
		form.addTags( new InputTag("item_quantity_"+(i+1),Html.HIDDEN,1));
	  }

	  Product.removeAllFromCart();
	  return form;
	  break;*/

  } 
  
	return null;  
}



Integrate.send = function(){
 document.forms[Integrate.fName].submit();
}


  function AutoComplete (el, datafunc){
	  this.datafunc=datafunc;  
	  this.id=el.getAttribute('id');
      el.setAttribute('autocomplete', 'off');
	  Event.add(el, 'blur', function(e){
          if (!e) e = window.event; 
		  AutoComplete.onBlur(this.id,e);
      });
      
      el.setAttribute('autocomplete', 'off');
     el.onkeyup   = function(e){ if (!e) e = window.event; return AutoComplete.onKeyUp  (this.id, e);};
      el.onkeydown = function(e){ if (!e) e = window.event; return AutoComplete.onKeyDown(this.id, e);};
      //el.onkeypress = function(e){ if (!e) e = window.event; return AutoComplete.onKeyPress(this.id, e);};
      
  }
  
 AutoComplete.resultEL = null; //DIV Element with results
 AutoComplete.activeID = null; //ID of active textbox (to reposition the container when needed) 
 AutoComplete.timerID = null;
 AutoComplete.autoArr = new Array();
 AutoComplete.highlightedline = 0; 
 AutoComplete.results=new Array();
 AutoComplete.disabled=false;
 
 AutoComplete.resetResults = function(){
	 AutoComplete.results=new Array();
 }
 AutoComplete.addResult = function(val){
	 AutoComplete.results[AutoComplete.results.length]=val;
 }
  
 AutoComplete.timeoutReached = function(id){
	 eval(AutoComplete.autoArr[id].datafunc);
	 AutoComplete.timerID=null;
	 //alert(Dom.get(id).form);
 }
 
 
 AutoComplete.onKeyDown= function(id,e){
  var keyCode = e.keyCode;

	    switch (keyCode) {
     		case 13:
     		 AutoComplete.disabled=false;
     		 break;
         // Up arrow
            case 38:
                e.returnValue = false;
                e.cancelBubble = true;
				AutoComplete.hightLight(-1);
				if (AutoComplete.activeID!=null && AutoComplete.isOpenResults()){
						Dom.get(id).value = AutoComplete.results[AutoComplete.highlightedline];
				}
                return false;
                break;
            
            
            // Down arrow
            case 40:
                e.returnValue = false;
                e.cancelBubble = true;
				AutoComplete.hightLight(1);                
				if (AutoComplete.activeID!=null && AutoComplete.isOpenResults()){
						Dom.get(id).value = AutoComplete.results[AutoComplete.highlightedline];
				}
                return false;
                break;		    
		    
       		case 27:
       		    AutoComplete.disabled=true;
   				AutoComplete.onBlur(null,null);  
                e.returnValue = false;
                e.cancelBubble = true;
              return false;
        }
        return true;
  }
 
  /*AutoComplete.onKeyPress=function(id,e){
      
	   var keyCode = e.keyCode;

	    switch (keyCode) {
       		case 40:
            case 38:
       		case 27:
              e.returnValue = false;
              e.cancelBubble = true;
              return false;
   
        }
  	  return true;
 }*/
  
  AutoComplete.onKeyUp=function(id,e){
      
	   var keyCode = e.keyCode;

	    switch (keyCode) {
       		case 40:
            case 38:
       		case 27:
              e.returnValue = false;
              e.cancelBubble = true;
              return false;
   
        }
        
      if (!AutoComplete.disabled){
      	if (AutoComplete.timerID!=null) clearTimeout(AutoComplete.timerID);
      	AutoComplete.timerID = setTimeout("AutoComplete.timeoutReached('"+id+"')",2000);
      	if (AutoComplete.resultEL!=null) Html.hideElement(AutoComplete.resultEL);  
      	if (AutoComplete.activeID!=id){
	      	AutoComplete.CreateDropdown(id);
      		AutoComplete.activeID=id;
  	  	}
	  }
  	  
  	  return true;
 }

 AutoComplete.onBlur=function(id,e) {
    if (AutoComplete.timerID!=null) clearTimeout(AutoComplete.timerID);
    if (AutoComplete.resultEL!=null) Html.hideElement(AutoComplete.resultEL);  
 }
  
 AutoComplete.init= function (attr){ 

  AutoComplete.resultEL = document.createElement('div');
  AutoComplete.resultEL.className = 'autocomplete'; // Don't use setAttribute()
  AutoComplete.resultEL.style.zIndex     = '9999';
  AutoComplete.resultEL.style.visibility = 'hidden';

  var els = document.getElementsByTagName('INPUT');
  for (var i=0; i<els.length; i++) {
    if( els[i].type.toLowerCase() == 'text' ) {
      var sLangAtt = els[i].getAttribute( attr );
      if( sLangAtt != null && sLangAtt.length > 0 ) {
	      AutoComplete.autoArr[ els[i].getAttribute('id') ]=new AutoComplete (els[i], sLangAtt);
      }
    }
  }
  
 }
 
  AutoComplete.isOpenResults=function(){
	return !Html.isHidden( AutoComplete.resultEL );	  
  }
 
 AutoComplete.setContent= function (){ 
    var total_html='<ul>';

   for(var i=0; i<AutoComplete.results.length; i++) { 
     total_html = total_html + '<li>' + AutoComplete.results[i] + '</li>';
   }
  total_html = total_html + '</ul>'
  AutoComplete.resultEL.innerHTML = total_html;
  AutoComplete.highlightedline = 0;
  if (AutoComplete.results.length<1) return;
  AutoComplete.hightLight(0);	  
  Html.showElement(AutoComplete.resultEL);
} 
 
AutoComplete.hightLight= function (ind){ 
  if (AutoComplete.resultEL==null || AutoComplete.results.length<1 ) return;	
  AutoComplete.resultEL.childNodes[0].childNodes[AutoComplete.highlightedline].className="";
  AutoComplete.highlightedline=AutoComplete.highlightedline + ind;
  
  if (AutoComplete.highlightedline>=AutoComplete.results.length) AutoComplete.highlightedline = 0;
  if (AutoComplete.highlightedline<0) AutoComplete.highlightedline = AutoComplete.results.length-1;
  AutoComplete.resultEL.childNodes[0].childNodes[AutoComplete.highlightedline].className="mgHighlighted";	
}


 
 //reposition the main div element
 AutoComplete.CreateDropdown=function(id){
	 var el=Dom.get(id);
     
     try{
      Dom.remove(AutoComplete.resultEL);
 	 }catch(err){}
     
     el.parentNode.insertBefore(AutoComplete.resultEL, el);
         
     // Position it
	 var pos = AutoComplete_GetPos(el);
     AutoComplete.resultEL.style.left       = pos.x + 'px';
     AutoComplete.resultEL.style.top        = (pos.y + el.offsetHeight) + 'px';
     AutoComplete.resultEL.style.width      = el.offsetWidth + 'px';
 }
    
    
    function AutoComplete_GetPos(e) {
		var obj = e;
		var curleft = 0;
		var curtop = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent){
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		}else{
			if (obj.x) curleft += obj.x;
	    	if (obj.y) curtop += obj.y;
    	}

		return {x:curleft, y:curtop};
   }