$(function () {
	$("div#header > div.search > input[type=text]").autocomplete("/knitted-products/search.html", {
		width: "380px",
		multiple: false,
		matchContains: true,
		scroll: true,
		scrollHeight: 250,
		mustMatch: false,
		delay: 150,
		extraParams: {
//			sbit_id: function() { return sbit_id; }
		},
		formatItem: function(row, i, max) {
			return row[1];
		},
		formatMatch: function(row, i, max) {
			return row[0] + ". " + row[1];
		},
		formatResult: function(row) {
			return row[1];
		}
	}).result(function(e, data, formatted) {
		document.location = "/knitted-products/product.html?code=" + data[0];
	});
});

function ValidateItem (obj, arr){
	var res;
	switch (arr[obj.attr("name")]){
		case "CheckEmptyness":
			res = CheckEmptyness(obj.val());
       	break;
		case "CheckEmail":
			res = (obj.val() == "") ? true : CheckEmail(obj.val());
       	break;
		case "CheckInteger":
			res = CheckInteger(obj.val());
       	break;
		case "CheckFloat":
			res = CheckFloat(obj.val());
       	break;
		case "":
			res = true;
       	break;
	}
	return res;
}

function CheckEmptyness(val){
	return (val.length < 3) ? false : true;
}
function CheckInteger(val){
	if (val == "") return false;
	return (val != "" && parseInt(val) == val) ? true : false;
}
function CheckFloat(val){
	if (val == "") return false;
	return (val != "" && parseFloat(val) == val) ? true : false;
}
function CheckEmail(e){
	e = e.toLowerCase();
	var ch="@";
	var count=0;
	var error=false;

	for (var i=0; i<e.length; i++){
		if (e.charAt(i)==ch || e.charAt(i)=="."){
			error = (count==0) ? true : error;
			ch = (ch==".") ? 0 : ch;
			ch = (e.charAt(i)=="@") ? "." : ch;
			count=0;
			continue;
		}
		count++;

		if ((e.charAt(i)<"a" || e.charAt(i)>"z") && (e.charAt(i)<"0" || e.charAt(i)>"9") && e.charAt(i)!="_" && e.charAt(i)!="-"){
			error = true;
			break;
		}
	}
	error = (count==0) ? true : error;
	error = (ch==0) ? error : true;
	return !error;
}

function str_replace (search, replace, subject ) { 
	if(!(replace instanceof Array)){ 
		replace=new Array(replace); 
		if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search 
			while(search.length>replace.length){ 
				replace[replace.length]=replace[0]; 
			} 
		} 
	} 
	
	if(!(search instanceof Array))search=new Array(search); 
	while(search.length>replace.length){
		replace[replace.length]=''; 
	} 

	if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well. 
		for(k in subject){ 
			subject[k]=str_replace(search,replace,subject[k]); 
		} 
		return subject; 
	} 

	for(var k=0; k<search.length; k++){ 
		var i = subject.indexOf(search[k]); 
		while(i>-1){ 
			subject = subject.replace(search[k], replace[k]); 
			i = subject.indexOf(search[k],i); 
		} 
	} 

	return subject; 
}
