function $(name) {
	return document.getElementById(name);
}
function rate(name,value) {
	$(name).value = value;
	stars = ['','one-star','two-stars','three-stars','four-stars','five-stars'];
	$(name + '-stars').className = 'star-rating ' + stars[value];
	return false;
}
function change_pic(idx, prodid) {
	obj = $('bigImg');
	obj.src = 'photos/'+prodid+'-'+idx+'-'+230+'.jpg';
}
function change_main(prodid) {
	obj = $('bigImg');
	obj.src = 'photos/'+prodid+'-'+230+'.jpg';
}
function change_pic_little(idofelement, idx, prodid) {
	obj = $(idofelement);
	obj.src = 'photos/'+prodid+'-'+idx+'-'+141+'.jpg';
}
function iconChange(n,v) {
	$(n).value = v;
	for(var i=1; i<4; i++) {
		if(i==v) {
			$(n+i).style.backgroundPosition = '0px -194px';
		}else{
			$(n+i).style.backgroundPosition = '0px 0px';
		}
	}
	return false;
}
function formCheck() {
	var err = '';
	if(!$('name').value) err += '"Name"\n';
	if(!$('email').value) err += '"Email"\n';
	if(!$('gender').value) err += '"Gender"\n';
	if(!$('handicap').value) err += '"Handicap"\n';
	if(!$('trajectory').value) err += '"Trajectory"\n';
	if(!$('tempo').value) err += '"Tempo"\n';
	if(!$('shaft').value) err += '"Shaft"\n';
	if(!$('flex').value) err += '"Flex"\n';
	if(!$('previously').value) err += '"Previously"\n';
	if(!$('comment').value) err += '"Comment"\n';
	if(!$('feel').value) err += '"Feel"\n';
	if(!$('forgiveness').value) err += '"Forgiveness"\n';
	if(!$('distance').value) err += '"Distance"\n';
	if(!$('accuracy').value) err += '"Accuracy"\n';
	if(!$('aesthetics').value) err += '"Aesthetics"\n';
	if(!$('overall').value) err += '"Overall"\n';
	if(!$('addressArea').value) err += '"Address Area"\n';
	if(!$('spin').value) err += '"Spin"\n';
	if(!$('topLine').value) err += '"Top Line"\n';
	if(!$('offset').value) err += '"Offset"\n';
	if(!$('swingSpeed').value) err += '"Swing Speed"\n';
	if(!$('launchAngle').value) err += '"Launch Angle"\n';
	if(!$('workability').value) err += '"Forgiveness & Workability"\n';
	if(!$('faceHeight').value) err += '"Face Height"\n';
	
	if(err) {
		alert('The following fields are empty:\n\n'+err);
		return false;
	}else{
		return true;
	}
}


function hoverStar(element, position){
	element = $(element);
	var stars = ['rating_onestar', 'rating_twostar', 'star-threestar', 'rating_fourstars', 'rating_fivestar'];
	element.className = stars[position];
}

function clearClass(element, parent){
	element = $(element);
	parent =  $(parent);
	var position = parent.value;
	var stars = ['rating_onestar', 'rating_twostar', 'star-threestar', 'rating_fourstars', 'rating_fivestar'];
	element.className = stars[position - 1];
}

function setProperty1(elem, value, thisElem) {
	elemString = elem;
	elem = $(elemString);
	elem.value = value;
	
	for(i = 1; i <= 3;i++) {
		var selector = "a."+elemString+i;	
		var obj = $$(selector);
		for(j in obj) {
			if((typeof(obj[j].className) == 'string' && obj[j].className.match(/active/)))
				obj[j].className = obj[j].className.replace(/\s?active/i, '');
		}		 	
	}
	thisElem.className = thisElem.className.replace(/active/i, '')+' active';
	
}

function setProperty(elem, value, thisElem) {
	var selector = '#'+elem+'Container a';
	var props = $$(selector);
	for(i in props) {
		if(typeof(props[i]) == 'object') {			
			if(props[i].hasClassName(elem+value)) {
			 props[i].addClassName('active');			 
			}
			else 
			 props[i].removeClassName('active');
		}
	}
	if($(elem))
	$(elem).value = value;
	
	
}


function forgotPass() {
	if($('emailFogotPass').value) {
		
		new Ajax.Request("ajaxForgotPass.php", {
			method: 'post',
			postBody: 'email='+escape($('emailFogotPass').value),
			onSuccess: function(t){
				
				if(t.responseText == 'success') {
				
				$('showMessage').innerHTML = 'Your password has been sent';
				} else {
					$('showMessage').innerHTML = 'This email '+$('emailFogotPass').value+' does not exists in our database';
				}
			}
			
		});
	}
	return false;
}


function getProducts(brand) {
	
	var opt = {
		method: 'get',
		onSuccess: function(t) {			
			$('productsSelect').innerHTML = t.responseText;
		}
	};
	
	new Ajax.Request('ajaxLatestReviews.php?brand='+brand, opt);
}

var Item = {
	clicked: false,
	init: function(url, button, brand, model){
	  if(!brand || !model) {
	  		brand = 'products_brand';
	  		model = 'products_model';
	  }
		var brandValue = $(brand).value;
		var modelValue = $(model).value;
		var errorStr = ''
		if(!brandValue) {
			errorStr = 'Please provide Brand.';
		}
		if(!modelValue)  {
			errorStr += '\nPlease provide Model.';
		}
		if(errorStr) {
			alert(errorStr);
			return false;
		}
		var buttonObj = $(button);
	   
		if (Item.clicked == true) {
			return true;	
		}
		
		//Item.clicked = true;
		lon();

		new Ajax.Request('updatePrices', {method: 'post',
		                   	   parameters : 'brand='+brandValue +'&model='+ modelValue,
		                       onComplete: function(originalRequest) {

		   
		                       // 	alert(originalRequest.responseText);

		                         var r = parseJSON(originalRequest.responseText);
							 
		                         if (r.error) {
		                         	loff();
		                         	alert(r.error);
		                         	return false;
		                         }
		                         
		                         
		                         r.r.each(function(driver)
		                         {
		                         	var appendHTML = 'prices_'+ driver.name;
		                         	if ($(appendHTML) == null) {
		                         		next;
		                         	}
                     	
									var input_0 = document.createElement('input');
									   input_0.name = driver.name +"_[0][item]";
									   input_0.className = "item_desc";
									   input_0.type = "text";
									   input_0.id = driver.name +"_uri";
									   input_0.value = driver.uri;
									$(appendHTML).appendChild( input_0 );
									
									
									var input_1 = document.createElement('input');
									   input_1.name = driver.name +"_[0][value]";
									   input_1.className = "item_price";
									   input_1.id = driver.name +"_price";
									   input_1.type = "text";
									   input_1.value = driver.price;
									$(appendHTML).appendChild( input_1 );			                         	
		                         	
									
									var input_0 = document.createElement('input');
									   input_0.value = " Update ";
									   input_0.onclick = function(){
									      javascript: Item.updatePrice(driver.uri, driver.name)
									   };
									   input_0.type = "button";
									$(appendHTML).appendChild( input_0 );
									
	                         
		                         	$('pricing_field').show();
		                         	loff();	
		                         });
		                         
		                        buttonObj.onclick = function()
		                         {
		                         	return Item.checkPrices();
		                         }
		                      }
		                 });

		return false;
	},
	updatePrice: function(priceId, engine)
	{
		if (uri == '') {
			alert('Please fill the URL of the product.');
			return false;
		}
		
		var uri = '';
		
		if ($(engine +"_uri") != null) {
			uri = $(engine +"_uri").value;
		}
				
		///
		/// Need to escape &, for HTTP compatibility
		uri = uri.replace(/&/g, ";");

		
		lon();
		
		new Ajax.Request('/search/SearchPrices.php?do=Single', {method: 'post',
		                       parameters : 'uri='+ uri +'&engine='+ engine,
		                       onComplete: function(originalRequest) {

			                         var r = parseJSON(originalRequest.responseText);
	
			                         if (r.error) {
			                         	loff();
			                         	alert(r.error);
			                         	return false;
			                         }		                       	

			                       	if (r.price && $(engine +'_price') != null) {
			                       		loff();
			                       		$(engine +'_price').value = r.price;
			                       	}

		   							return false;
		                       }
		});

		return false;		
	},
	checkPrices: function(insider) {
		
		var alerts = false;
		var alertItems = 0;
		var item = '';
		
		$$('div#pricing_field ul li div').each(function(field) {
			///
			/// We have item with uri and w/o price
			if (field.childNodes[(insider == true ? 1 : 0)].value != '' && field.childNodes[(insider == true ? 3 : 1)].value == '')  {
				alerts = true;				
				alertItems++;
				item = field.childNodes[(insider == true ? 1 : 0)].id;
			}
		});
		
		
		if (alerts == true) {
			if (alertItems > 1) {
				alert('There`re items w/o price. Please click on the `Update` button, to search for price.');
				return false;
			} else {
				if (confirm('You forgot to add price in one of the fields, do you want to search it automaticly or you`ll add it manually.')) {
					var namePart = item.split('_');
					Item.updatePrice(0, namePart[0]);
					return false;
 				} else {
 					return true;
 				}
			}
		} else {
			return true;
		}

	     $('save_bnt').onclick = function()
	     {
	     	return true;
	     }		
		return false;
	}
}




function parseJSON(str)
{
	if (str == '')
	    return false;

	return new Function('return {' + str +'}')();
}

function lon(target)
{


	if (!document.getElementById('adminarea') == null) {
		return false;
	}
//
	//try {
		if (!target)
			target = this;

		lsetup(target);

		if (!target._lon_disabled_arr)
			target._lon_disabled_arr = new Array();
		else if (target._lon_disabled_arr.length > 0)
			return true;

		if (document.getElementById("loaderContainer"))
			target.document.getElementById("loaderContainer").style.display = "";

	//} catch (e) {
	///	return false;
//	}

	return true;
}

function loff(target)
{


	//try {
		if (!target)
			target = this;

		target.document.getElementById("loaderContainer").style.display = "none";

	//} catch (e) {
	//	return false;
	//}
	return true;
}

function lsetup_handler(e)
{
	lsetup(this);
	return true;
}

function lsetup(target)
{
	//try {
		if (!target)
			target = this;

		var o_set = target.document.getElementById('loaderContainerWH');
		var o_getH = target.document.getElementsByTagName('BODY')[0];

//		o_set.style.height = o_getH.scrollHeight;
	//} catch (e) {
	//}
}

function appendImage(imageUrl, container){
	container = $(container);
	var image = new Image();
	image.src = imageUrl;
	container.innerHTML = '';
	container.appendChild(image);
}