// eShop - Kernel - Created by RaZEr in 2003 .

function str_replace(str_fr,str_to,str_dest) {
         while ((pos = str_dest.indexOf(str_fr))>0) str_dest = str_dest.substr(0,pos)+str_to+str_dest.substr(pos+1);
         return str_dest;
         }

function DTF_GetDaysInMonth (year,month) {
         thisDate = new Date(year,month,0);
         return thisDate.getDate();
         }
         
function DTF_FormatNumber (number) {
         str = number.toString();
         return (str.length < 2)?"0"+str:str;
         }

function DTF_MakeTimestamp (milliseconds) {
         curDate = new Date(milliseconds);
         return curDate.getFullYear()+"-"+DTF_FormatNumber(curDate.getMonth()+1)+"-"+DTF_FormatNumber(curDate.getDate())+" "+
                DTF_FormatNumber(curDate.getHours())+":"+DTF_FormatNumber(curDate.getMinutes())+":"+DTF_FormatNumber(curDate.getSeconds());
         }

function FDI_Process (elemId,newValue) {
         curDate = new Date();
         document.getElementById(elemId).value = DTF_MakeTimestamp(curDate.getTime()+(newValue*1000));
         }

function FDP_RefreshDaysCombo (selectElem,daysCount) {
         if (selectElem.options.length < daysCount) {
            for (i=selectElem.options.length-1;i<=daysCount;i++) selectElem.options[i] = new Option(i,i,false,false);
            } else if (selectElem.options.length > daysCount) {
            for (i=selectElem.options.length-1;i>daysCount;i--) {
                if (selectElem.options[i].selected) selectElem.options[i-1].selected = true;
                selectElem.options[i] = null;
                }
            }
         }

function FDP_Refresh (elemName,sender)
{
	fr_day = document.getElementById(elemName+"_fr_day");
	fr_month = document.getElementById(elemName+"_fr_month");
	fr_year = document.getElementById(elemName+"_fr_year");
	fr_date = new Date(fr_year.value,fr_month.value-1,fr_day.value);
	
	to_day = document.getElementById(elemName+"_to_day");
	to_month = document.getElementById(elemName+"_to_month");
	to_year = document.getElementById(elemName+"_to_year");
	to_date = new Date(to_year.value,to_month.value-1,to_day.value);
	
	//alert(fr_date+'--'+to_date);
	
 	if (to_date.getTime()-fr_date.getTime() < 86400000)
 	{
 		if (sender == 0)
 		{
 			// init
 			to_date = new Date();
 			fr_date = new Date(to_date.getTime()-86400000*30);
 		}
 		else
 		{
 			fr_date = new Date(to_date.getTime()-86400000);
 			to_date = new Date(fr_date.getTime()+86400000);
 		}
 		if ((sender == 1) || (sender == 0))
 		{
 			// from left
 			to_day.value = DTF_FormatNumber(to_date.getDate());
 			to_month.value = DTF_FormatNumber(to_date.getMonth()+1);
 			to_year.value = to_date.getFullYear();
 		}
 		if ((sender == 2) || (sender == 0))
 		{
 			// from right
 			fr_day.value = DTF_FormatNumber(fr_date.getDate());
 			fr_month.value = DTF_FormatNumber(fr_date.getMonth()+1);
 			fr_year.value = fr_date.getFullYear();
 		}
 	}
 	FDP_RefreshDaysCombo(fr_day,DTF_GetDaysInMonth(fr_year.value,fr_month.value));
 	FDP_RefreshDaysCombo(to_day,DTF_GetDaysInMonth(to_year.value,to_month.value));
}

/*
* @desc Call a tool/wizard for input element.
*/
function UseTool (url, target, width, height)
{
	toolWin = window.open(url,'toolwin','width='+width+',height='+height+
		',resizable=no,scrollbars=no,menubar=no,toolbar=no,location=no,status=no');
	toolWin.SubmitValue = function (value)
	{
		var targetObj = document.getElementById(target);
		if (targetObj && targetObj.value !== undefined)
		{
			targetObj.value = value;
		}
	};
}

/*
* @desc Dates operations
*/

Dates = new Object();
Dates.GetDaysInMonth = function (date)
{
	return (new Date(date.getFullYear(),date.getMonth()+1,0)).getDate();
};

/*
* @desc Events operations
*/

Events = new Object();
Events.AddHandler = function (object, event, handler)
{
	if (object.addEventListener)
	{
		object.addEventListener(event,handler,false);
	}
	else
	{
		eval('object.on'+event+' = handler;');
	}
};

/*
* @desc String functions
*/

Strings = new Object();

Strings.NameToLogin = function (str)
{
	var func = function (c)
	{
		var from = 'àáâãäå¸æçèéêëìíîïðñòóôõö÷øùúûüýþÿ!@$ ';
		var to1x = 'abvgdee0ziyklmnoprstufhc123#i#e45ias_';
		var to2x = 'zhchshshyuya';
		var index = from.indexOf(c);
		if (index != -1)
		{
			var repl = to1x.substr(index,1);
			if (repl != '#')
			{
				var m = repl.match(/^\d$/); //alert(m);
				return !m ? to1x.substr(index,1) : to2x.substr(m*2,2);
			}
			else
			{
				return '';
			}
		}
		else
		{
			return '';
		}
	}; 
	return str.replace(/[^a-z0-9_\-]/gi,func);
};

Strings.Repeat = function (str, count)
{
	var out = '';
	for (var i=0; i < count; i++)
	{
		out += str;
	}
	return out;
};

/*
* @desc Date Element
*/

function FormDate (name, value, isOptional)
{	
	this.name = name;
	this.value = value;
	this.isOptional = isOptional;
	this.date = new Date(value ? value*1000 : (new Date()).getTime());
	this.prefix = 'date'+Math.round(Math.random()*1000);
	this.months = new Array('ßíâàðü','Ôåâðàëü','Ìàðò','Àïðåëü','Ìàé','Èþíü','Èþëü','Àâãóñò','Ñåíòÿáðü','Îêòÿáðü','Íîÿáðü','Äåêàáðü');
	
	this.BuildUI = function ()
	{
		// Base
		var out = '';
		
		if (this.isOptional)
		{
			out += '<input type="checkbox" id="'+this.GetName('switch')+'" '+(this.value ? 'checked ' : '')+'/>';
		}
		
		out += '<input type="hidden" id="'+this.GetName('date')+'" name="'+this.name+'" value="'+this.value+'" />';
		
		out += '<span id="'+this.GetName('box')+'">';
		
		// Days
		var days = Dates.GetDaysInMonth(this.date);
		out += '<select id="'+this.GetName('day')+'" value="">';
		for (var i=1; i<=days; i++)
		{
			out += '<option value="'+i+'">'+i+'</option>';
		}
		out += '</select>';
		
		// Months
		out += '<select id="'+this.GetName('month')+'" value="">';
		for (var i=0; i<=11; i++)
		{
			out += '<option value="'+i+'">'+this.FormatNumber(i+1,2)+' - '+this.months[i]+'</option>';
		}
		out += '</select>';
		
		// Years
		var from = this.date.getFullYear()-5;
		var to = (new Date()).getFullYear()+5;
		out += '<select id="'+this.GetName('year')+'" value="">';
		for (var i=from; i<=to; i++)
		{
			out += '<option value="'+i+'">'+i+'</option>';
		}
		out += '</select>';
		
		out += '</span>';
		
		document.write(out);
		
		// Tune
		var dayObj = this.GetUI('day');
		var monthObj = this.GetUI('month');
		var yearObj = this.GetUI('year');
		
		dayObj.value = this.date.getDate();
		monthObj.value = this.date.getMonth();
		yearObj.value = this.date.getFullYear();
		
		var self = this;
		dayObj.onchange = function () { self.SetDay(this.value); }
		monthObj.onchange = function () { self.SetMonth(this.value); }
		yearObj.onchange = function () { self.SetYear(this.value); }
		
		if (this.isOptional)
		{
			var switchObj = this.GetUI('switch');
			switchObj.onclick = function () { self.SetState(); }
			switchObj.onchange = function () { self.SetState(); }
			this.SetState();
		}
	};
	
	this.ClearValue = function ()
	{
		this.GetUI('date').value = '';
	};
	
	this.FormatNumber = function (num, len)
	{
		var str = num.toString();
		return (str.length < len) ? Strings.Repeat('0',len-str.length)+str : str;
	};
	
	this.GetUI = function (name)
	{
		return document.getElementById(this.GetName(name));
	};
	
	this.GetDate = function ()
	{
		return Math.round(this.date.getTime()/1000);
	};
	
	this.GetName = function (name)
	{
		return this.prefix+name;
	};
	
	this.SetValue = function ()
	{
		this.GetUI('date').value = this.GetDate();
	};
	
	this.SetDay = function (day)
	{
		this.date.setDate(day);
		this.SetValue();
	};
	
	this.SetMonth = function (month)
	{
		this.date.setMonth(month);
		if (this.date.getMonth() != month)
		{
			this.SetMonth(month); // unclean method
		}
		this.UpdateUI();
		this.SetValue();
	};
	
	this.SetYear = function (year)
	{
		this.date.setFullYear(year);
		this.UpdateUI(); // update days count (feb 28)
		this.SetValue();
	};
	
	this.SetState = function ()
	{
		checkbox = this.GetUI('switch');
		groupbox = this.GetUI('box');
		if (checkbox.checked)
		{
			groupbox.style.visibility = 'visible';
			this.SetValue();
		}
		else
		{
			groupbox.style.visibility = 'hidden';
			this.ClearValue();
		}
	}
	
	this.UpdateUI = function ()
	{
		var ui = this.GetUI('day');
		var srcDays = ui.options.length;
		var dstDays = Dates.GetDaysInMonth(this.date);
		//alert('UI: '+srcDays+'->'+dstDays);
		if (dstDays > srcDays)
		{
			// add
			for (var i=srcDays+1; i <= dstDays; i++)
			{
				ui.options[i-1] = new Option(i,i,false,false);
			}
		}
		else if (dstDays < srcDays)
		{
			// remove
			for (var i=srcDays; i >= dstDays+1; i--)
			{
				if (ui.options[i-1].selected)
				{
					ui.options[i-2].selected = true;
				}
				ui.options[i-1] = null;
			}
		}
	};
	
	this.BuildUI();
}

/*
* @desc
*/

function FormPassword (name, value)
{
	this.name = name;
	this.value = value;
	
	this.prefix = 'date'+Math.round(Math.random()*1000);
	
	this.colors = new Array('#FFFFFF','#FF0000','#FF8A00','#FFD100','#BACF00','#40BF00');
	this.ranges = {
		'LettersEnSmall': 'abcdefghigklmnopqrstuvwxyz',
		'LennersEnBig': 'ABCDEFGHIGKLMNOPQRSTUVWXYZ',
		'LettersRuSmall': 'àáâãäå¸æçèéêëìíîïðñòóôõö÷øùúûüýþÿ',
		'LettersRuBig': 'ÀÁÂÃÄÅ¨ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß',
		'Digits': '0123456789'
		};
	this.sequences = {
		'KeyboardEnSmall': 'qwertyuiopasdfghjklzxcvbnm',
		'KeyboardEnBig': 'QWERTYUIOPASDFGHJKLZXCVBNM',
		'KeyboardRuSmall': 'éöóêåíãøùçõúôûâàïðîëäæýÿ÷ñìèòüáþ',
		'KeyboardRuBig': 'ÉÖÓÊÅÍÃØÙÇÕÚÔÛÂÀÏÐÎËÄÆÝß×ÑÌÈÒÜÁÞ'
		};
	this.stupid = '1234567890 admin anonimous cccp guest god host fsb kgb login none null password root swordfish zerocool';
	
	this.BuildUI = function ()
	{
		var out = '<table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td>';
		out += '<input type="text" id="'+this.GetName('Field')+'" name="'+this.name+'" value="'+this.value.replace(/\"/,'&quot;')+'" />';
		out += '</td><td>';
		out += '<div class="CntGauge"><div id="'+this.GetName('Progress')+'" class="Progress"></div></div>';
		out += '</td></tr></tbody></table>';
		document.write(out);
		
		var self = this;
		var field = this.GetObject('Field');
		var handler = function (e) { return self.UpdateRank(); };
		Events.AddHandler(field,'keyup',handler);
		Events.AddHandler(field,'keypress',handler);
		Events.AddHandler(field,'change',handler);
		
		this.UpdateRank();
	};
	
	this.GetName = function (name)
	{
		return this.prefix+name;
	};
	
	this.GetObject = function (name)
	{
		return document.getElementById(this.prefix+name);
	};
	
	this.Rank = function (pass)
	{
		var inRanges = 0;
		var inSequences = 0;
		var inStupids = 0;
		var symbols = 0;
		var result = 0;
		
		if (pass.length > 1)
		{
			// Ranges
			for (var range in this.ranges)
			{
				if (pass.search(new RegExp('['+this.ranges[range]+']')) != -1)
				{
					inRanges++;
					symbols += this.ranges[range].length;
				}
			}
			if (pass.search(new RegExp('[^a-zà-ÿ0-9]+','i')) != -1)
			{
				inRanges++;
				symbols += 128; // approx: 256-59*2-10
			}
			
			if (inRanges == 1)
			{
				// Stupid
				if (pass.search(new RegExp('^(.)\\1{'+(pass.length-1)+'}$')) == -1)
				{
					// Sequences
					var inSequences = 0;
					for (var sequence in this.sequences)
					{
						if (this.sequences[sequence].search(new RegExp(pass.replace(/[^\w]/,''))) != -1)
						{
							inSequences++;
						}
					}
				}
				else
				{
					inSequences = 1;
					inStupids = 1;
				}
			}
			if ((this.stupid.indexOf(pass) != -1) || (this.stupid.toUpperCase().indexOf(pass) != -1))
			{
				inStupids = 1;
			}
			
			// Analyze
			var modifer = 1;
			if (inSequences)
			{
				modifer -= 0.1; // <-- sequence effect
			}
			if (inStupids)
			{
				modifer -= 0.25; // <-- stupid effect
			}
			modifer += inRanges/2.8; // <-- range effect
			modifer -= ((256/6)-(symbols/inRanges))*0.025; // <-- symbols effect
			
			result = Math.ceil((pass.length/3.2)*modifer); // <-- length effect
		}
		else
		{
			result = 1;
		}
		//alert(result+' (mod: '+modifer+', ranges: '+inRanges+' seqs: '+inSequences+' stupids: '+inStupids);
		return (result > 5) ? 5 : result;
		//return result+' (mod: '+modifer+', ranges: '+inRanges+' seqs: '+inSequences+' stupids: '+inStupids;
	};
	
	this.UpdateRank = function ()
	{
		var rank = this.Rank(this.GetObject('Field').value);
		var progress = this.GetObject('Progress');
		progress.style.width = (rank*20)+'px';
		progress.style.backgroundColor = this.colors[rank];
	};
	
	// Constructor
	this.BuildUI();
}
