$(document).ready(function(){
	InitSlideDrop();
	//initTabs();  // RNG
	initScrollGallery();
	initAutoScalingNav({
		menuId: "nav",
		liHovering: true,
		flexible: true,
		equalLinks: false,
		sideClasses: true,
		spacing: 1
	});
	initAutoScalingNav({
		menuId: "navbar",
		sideClasses: true,
		minPaddings: 10
	});
	//initClearInputs();
	iniStarRating();
	initphrase();
	initCustomForms();
	ieHover();
	addClass({
		tagName:'a',
		tagClass:'opener',
		classAdd:'state-active',
		addToParent:true
	});
	//initSelection();
	showGreetingMsg();
	getAccountInfo();
	changeSearchBoxBackground();
});

function initSelection(){
	$('#sidebar').each(function(){
		var sidebar = $(this);
		var holder = $('.selection-list', sidebar);
		var holderList = $('li', holder);
		var btnClear = $('a.clear', sidebar);
		
		$('.item-list .slide li').each(function(){
			$(this).click(function(){
				_this = $(this);
				var flag = true
				var text = _this.html();
				
				holderList.each(function(){
					if($(this).html() == text) flag = false;
				});
				if (flag){
					$('<li>').html(text).appendTo(holder);
					holderList = $('li', holder);
					btnRemove();
				}
				return false;
			});
		});
		
		btnClear.click(function(){
			holder.html('');
			return false;
		});
		
		function btnRemove(){
			holderList.click(function(){
				$(this).remove();
				return false;
			});
		}
		
		btnRemove();
	});
}

/*IE 6 hover plagin*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}',58,58,'||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'),0,{}))
/*parametrs [selector, hover_class]*/
function ieHover() {
	hoverForIE6(".product-list li", "hover");
}

// add class Click
function addClass (_options) {
	var _tagName = _options.tagName;
	var _tagClass = _options.tagClass;
	var _classAdd = _options.classAdd;
	var _addToParent = false || _options.addToParent;
	var _el = document.getElementsByTagName(_tagName);
	if (_el) {
		for (var i=0; i < _el.length; i++) {
			if (_el[i].className.indexOf(_tagClass) != -1) {
				_el[i].onclick = function() {
					if (_addToParent) {
						if (this.parentNode.className.indexOf(_classAdd) == -1) {
							this.parentNode.className += ' '+_classAdd;
						} else {
							this.parentNode.className = this.parentNode.className.replace(_classAdd,'');
						}
					} else {
						if (this.className.indexOf(_classAdd) == -1) {
							this.className += ' '+_classAdd;
						} else {
							this.className = this.className.replace(_classAdd,'');
						}
					}
					return false;
				}
			}
		}
	}
}


// tabs
function initTabs() {
	$('ul.tabset').each(function(){
		var list = $(this);
		var links = list.find('a.tab');
		links.each(function() {
			var link = $(this);
			var href = link.attr('href');
			var tab = $(href);
			if(link.hasClass('active')) tab.show();
			else tab.hide();
			link.click(function(){
				links.filter('.active').each(function(){
					$($(this).removeClass('active').attr('href')).hide();
				});
				link.addClass('active');
				tab.show();
				initScrollGallery();
				return false;
			});
		});
	});
}

function initphrase(){
	var duration = 2500;
	if(!($.browser.msie && $.browser.version < 9)){
		$('blockquote.lopez-quote').each(function(){
			$(this).css('opacity', 0).animate({'opacity': 1}, {queue: false, duration: duration});
		});
	}
}

// scrolling init
function initScrollGallery(){
	jQuery('div.gallery').scrollGallery({
		sliderHolder: 'div.frame',
		slider:'>ul',
		slides:'>li',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		generatePagination:'.switherHolder',
		step:4
	});
}

function iniStarRating(){
	var rates = document.getElementsByTagName("ul");
	for (i = 0; i < rates.length; i ++){
		if (rates[i].className.indexOf("star-rating") != -1){
			rates[i]._lis = rates[i].getElementsByTagName("li");
			
			rates[i].onmouseover = function(){
				for (k = 0; k < this._lis.length; k++){
					if (this._lis[k].className.indexOf("active") != -1){
						this._active = this._lis[k];
						this._lis[k].className = this._lis[k].className.replace("active", "");
					}
				}
			}
			rates[i].onmouseout = function() {
				if (this._active && this._active.className.indexOf("active") == -1){
					this._active.className += " active";
				}
			}
		}
	}
}

function initClearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:false,
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		splitCount:false,
		afterInit:false,
		vertical:false,
		step:1
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;
		var _splitCount = _options.splitCount;

		// gallery init
		if(!_slides.length) return;

		if(_splitCount) {
			var curStep = 0;
			var newSlide = $('<slide>').addClass('split-slide');
			_slides.each(function(){
				newSlide.append(this);
				curStep++;
				if(curStep > _splitCount-1) {
					curStep = 0;
					_slider.append(newSlide);
					newSlide = $('<slide>').addClass('split-slide');
				}
			});
			if(curStep) _slider.append(newSlide);
			_slides = _slider.children();
		}

		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=$(this).outerWidth(true);
			_sumHeight+=$(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = $('<ul>');
			for(var i=0; i<_stepCount; i++) $('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
}

// init slide drop
function InitSlideDrop(){
	var holder = $('#nav'),
		_speed = 100;
	holder.find('>li').each(function (_i){
		var hold = $(this),
			drop = hold.find('.drop'),
			_h = drop.height(),
			_t, _t1;
		drop.height(0);

		hold.mouseenter(function (){
			if (_t)clearTimeout(_t);
			_t1 = setTimeout(function(){
				pos(hold);
				drop.show().animate({height: _h}, {queue:false, duration:_speed});
			}, 300);
		}).mouseleave(function (){	
			if (_t)clearTimeout(_t);
			if (_t1)clearTimeout(_t1);
			_t = setTimeout(function(){
				//drop.animate({height: 0}, {queue:false, duration:_speed, complete:function(){$(this).hide();}});
				drop.height(0);
			}, 20);
		});
	});
	function pos(obj){
		drop = obj.find('.drop');
		var _beg = obj.position().left + parseInt(drop.css('left'));
		var _end = holder.width() - _beg - drop.width();
		if (_beg < 0) drop.css('left', parseInt(drop.css('left'))-_beg)
		if (_end < 0) drop.css('left', -(obj.position().left + drop.width())+ holder.width())
	};
};

//init autoscaling nav
function initAutoScalingNav(o) {
	if (!o.menuId) o.menuId = "nav";
	if (!o.tag) o.tag = "a";
	if (!o.spacing) o.spacing = 0;
	if (!o.constant) o.constant = 0;
	if (!o.minPaddings) o.minPaddings = 0;
	if (!o.liHovering) o.liHovering = false;
	if (!o.sideClasses) o.sideClasses = false;
	if (!o.equalLinks) o.equalLinks = false;
	if (!o.flexible) o.flexible = false;
	var nav = document.getElementById(o.menuId);
	if(nav) {
		nav.className += " scaling-active";
		var lis = nav.getElementsByTagName("li");
		var asFl = [];
		var lisFl = [];
		var width = 0;
		for (var i=0, j=0; i<lis.length; i++) {
			if(lis[i].parentNode == nav) {
				var t = lis[i].getElementsByTagName(o.tag).item(0);
				asFl.push(t);
				asFl[j++].width = t.offsetWidth;
				lisFl.push(lis[i]);
				if(width < t.offsetWidth) width = t.offsetWidth;
			}
			if(o.liHovering) {
				lis[i].onmouseover = function() {
					this.className += " hover";
				}
				lis[i].onmouseout = function() {
					this.className = this.className.replace("hover", "");
				}
			}
		}
		var menuWidth = nav.clientWidth - asFl.length*o.spacing - o.constant;
		if(o.equalLinks && width * asFl.length < menuWidth) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].width = width;
			}
		}
		width = getItemsWidth(asFl);
		if(width < menuWidth) {
			var version = navigator.userAgent.toLowerCase();
			for (var i=0; getItemsWidth(asFl) < menuWidth; i++) {
				asFl[i].width++;
				if(!o.flexible) {
					asFl[i].style.width = asFl[i].width + "px";
				}
				if(i >= asFl.length-1) i=-1;
			}
			if(o.flexible) {
				for (var i=0; i<asFl.length; i++) {
					width = (asFl[i].width - o.spacing - o.constant/asFl.length)/menuWidth*100;
					if(i != asFl.length-1) {
						lisFl[i].style.width = width + "%";
					}
					else {
						if(navigator.appName.indexOf("Microsoft Internet Explorer") == -1 || version.indexOf("msie 8") != -1 || version.indexOf("msie 9") != -1)
							lisFl[i].style.width = width + "%";
					}
				}
			}
		}
		else if(o.minPaddings > 0) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].style.paddingLeft = o.minPaddings + "px";
				asFl[i].style.paddingRight = o.minPaddings + "px";
			}
		}
		if(o.sideClasses) {
			lisFl[0].className += " first-child";
			lisFl[0].getElementsByTagName(o.tag).item(0).className += " first-child-a";
			lisFl[lisFl.length-1].className += " last-child";
			lisFl[lisFl.length-1].getElementsByTagName(o.tag).item(0).className += " last-child-a";
		}
		nav.className += " scaling-ready";
	}
	function getItemsWidth(a) {
		var w = 0;
		for(var q=0; q<a.length; q++) {
			w += a[q].width;
		}
		return w;
	}
}


// custom form
var _selectHeight = 17;
var all_selects = false;
var active_select = null;
var selectText = "please select";

function initCustomForms() {
	getElements();
	separateElements();

	if( !navigator.userAgent.match(/Android/i) &&
	 !navigator.userAgent.match(/webOS/i) &&
	 !navigator.userAgent.match(/iPhone/i) &&
	 !navigator.userAgent.match(/iPod/i) &&
	 !navigator.userAgent.match(/iPad/i)
 	){
		replaceSelects();
	}else{
		var t = $("#prdRingSize #size");
		if(t.length > 0){
			t.css("left","0px");
			t.css("background-image","url(/media/ice/images/spacer/spacer.gif)");
		}
	}

	window.cfReady = true;
}

function refreshCustomForms() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < selects.length; i++) {
			var newText = document.createElement('div');
			if (selects[i].options[selects[i].selectedIndex].title.indexOf('image') != -1) {
				newText.innerHTML = '<img src="'+selects[i].options[selects[i].selectedIndex].title+'" alt="" />';
				newText.innerHTML += '<span>'+selects[i].options[selects[i].selectedIndex].text+'</span>';
			} else {
				newText.innerHTML = selects[i].options[selects[i].selectedIndex].text;
			}
			document.getElementById("mySelectText"+i).innerHTML = newText.innerHTML;
		}
	}
}

// getting all the required elements
function getElements() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < inputs.length; i++) {
			inputs[i].className = inputs[i].className.replace('outtaHere','');
			if(inputs[i]._ca) inputs[i]._ca.parentNode.removeChild(inputs[i]._ca);
			else if(inputs[i]._ra) inputs[i]._ra.parentNode.removeChild(inputs[i]._ra);
		}
		for(i = 0; i < selects.length; i++) {
			selects[i].replaced = null;
			selects[i].className = selects[i].className.replace('outtaHere','');
			selects[i]._optionsDiv._parent.parentNode.removeChild(selects[i]._optionsDiv._parent);
			selects[i]._optionsDiv.parentNode.removeChild(selects[i]._optionsDiv);
		}
	}

	// reset state
	inputs = new Array();
	selects = new Array();
	labels = new Array();
	radios = new Array();
	radioLabels = new Array();
	checkboxes = new Array();
	checkboxLabels = new Array();
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);}
		for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
		for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
					++rl;
				}
			}
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
					++cl;
				}
			}
		}
	}
}


//check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}


function replaceSelects() {
	/* move from old initCustomForms  */
	var _selects = document.getElementsByTagName('select');
	/* End of move from old initCustomForms  */
	var optionCtnDiv =  document.createElement("div");
	optionCtnDiv.id = "optionCtnDiv";	

	for(var q = 0; q < selects.length; q++) {
		if (!selects[q].replaced && selects[q].offsetWidth) {
			selects[q]._number = q;
			//create and build div structure
			var selectArea = document.createElement("div");
			var left = document.createElement("span");
			left.className = "left";
			selectArea.appendChild(left);

			var disabled = document.createElement("span");
			disabled.className = "disabled";
			selectArea.appendChild(disabled);

			selects[q]._disabled = disabled;
			var center = document.createElement("span");
			var button = document.createElement("a");
			
			button.tabIndex = selects[q].tabIndex;
						
			var text = document.createTextNode(selectText);
			center.id = "mySelectText"+q;

			var stWidth = selects[q].offsetWidth;
			selectArea.style.width = stWidth + "px";
			if (selects[q].parentNode.className.indexOf("type2") != -1){
				button.href = "javascript:showOptions("+q+",true)";
			} else {
				button.href = "javascript:showOptions("+q+",false)";
			}
			button.className = "selectButton";
			selectArea.className = "selectArea";

			selectArea.className += " " + selects[q].className;
			selectArea.id = "sarea"+q;
			center.className = "center";
			center.appendChild(text);
			selectArea.appendChild(center);
			selectArea.appendChild(button);

			//hide the select field
			selects[q].className += " outtaHere";

			//add tab event handler
			$('.selectButton',selectArea).mousedown(selectTabMouseHandler);	
			$('.selectButton',selectArea).focus(selectTabFocusHandler);														
			//$('.selectButton',selectArea).focusout(selectTabFocusOutHandler);
			//$(selects[q]).focus(function(){return false;});	
			//end of tab event handler
			
			//insert select div
			selects[q].parentNode.insertBefore(selectArea, selects[q]);
			//build & place options div

			var optionsDiv = document.createElement("div");
			var optionsList = document.createElement("ul");
			optionsDiv.innerHTML += "<div class='select-top'><div></div></div>";
			optionsDiv.appendChild(optionsList);

			selects[q]._optionsDiv = optionsDiv;
			selects[q]._options = optionsList;

			optionsDiv.style.width = stWidth + "px";
			optionsDiv._parent = selectArea;

			optionsDiv.className = "optionsDivInvisible";
			optionsDiv.id = "optionsDiv"+q;


			populateSelectOptions(selects[q]);
			optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
			
			/* move from old initCustomForms  */
			//var _selects = document.getElementsByTagName('select');
			var _SelctClassName = '';			
			if (_selects) {
				//for (var i = 0; i < _selects.length; i++) {
					if (_selects[q].className != '' && _selects[q].className != null){
						//indexOf('outtaHere')
						var classNameArr = _selects[q].className.split(' ');
						//_SelctClassName[i] = '';
						if(classNameArr != null && classNameArr.length > 0){
							for(var k = 0; k < classNameArr.length; k++){
								if(classNameArr[k].indexOf('outtaHere') == -1 && classNameArr[k] != ''){
									_SelctClassName = _SelctClassName+' drop-'+classNameArr[k];
								}
							}
						}
					}
				//}
				//for (var i = 0; i < _SelctClassName.length; i++) {
				//	var _selectDrop = document.getElementById('optionsDiv'+i);
				//	if (_selectDrop) {
				//		if (_SelctClassName[i]){ 
				//			_selectDrop.className += _SelctClassName[i];
				//		}
				//	}
				//}
				optionsDiv.className = optionsDiv.className+_SelctClassName;
				
			}			
			/* end of moving from  old initCustomForms */
			
			optionCtnDiv.appendChild(optionsDiv);
			//document.body.appendChild(optionsDiv);
			selects[q].replaced = true;
		}
		all_selects = true;//seems it should not be in the loop
	}
	document.body.appendChild(optionCtnDiv);
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";
	
	for(var w = 0; w < me.options.length; w++) {
		
		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt;
		if (me.options[w].title.indexOf('image') != -1) {
			optionTxt = document.createElement('img');
			optionSpan = document.createElement('span');
			optionTxt.src = me.options[w].title;
			optionSpan = document.createTextNode(me.options[w].text);
		} else {
			optionTxt = document.createTextNode(me.options[w].text);
		}
		
		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
		if (me.options[w].title.indexOf('image') != -1) {
			optionLink.appendChild(optionTxt);
			optionLink.appendChild(optionSpan);
		} else {
			optionLink.appendChild(optionTxt);
		}
		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	//set selected option index
	var openedSelect = document.getElementById("optionsDiv"+selectNo);
	if(openedSelect){
		$(openedSelect).attr("selectedIndex",linkNo);
	}
	
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
		textVar.appendChild(optionSpan);
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
	}
	if (window.cfReady && all_selects && selectField.onchange) {
		selectField.onchange();
		updateCustomizedSelectOnChange();
	}
}

function updateCustomizedSelectOnChange(){
	$('#mySelectText1').html($('#prefix :selected').text());
	$('#mySelectText2').html($('#var_state :selected').text());
	$('#mySelectText3').html($('#COUNTRYSET :selected').text());
}

//showing options
function showOptions(g) {
		_elem = document.getElementById("optionsDiv"+g);
		var divArea = document.getElementById("sarea"+g);
		if (active_select && active_select != _elem) {
			active_select.className = active_select.className.replace('optionsDivVisible',' optionsDivInvisible');
			active_select.style.height = "auto";
		}
		if(_elem.className.indexOf("optionsDivInvisible") != -1) {
			_elem.style.left = "-9999px";
			
			//_elem.style.top = findPosY(divArea) + _selectHeight + 'px';
			
			//End of Detect select position
			
			_elem.className = _elem.className.replace('optionsDivInvisible','');
			_elem.className += " optionsDivVisible";
			
			//Detect select position
			var top = findPosY(divArea) + _selectHeight;
			var windowHeight = $(window).height();
			var scrollDown = $(window).scrollTop();
			
			if((windowHeight + scrollDown - top) < $(_elem).height()){
				_elem.style.top = findPosY(divArea) - $(_elem).height() + 'px';
			}else{
				_elem.style.top = findPosY(divArea) + _selectHeight + 'px';
			}	
			
			/*if (_elem.offsetHeight > 200)
			{
				_elem.style.height = "200px";
			}*/
			_elem.style.left = findPosX(divArea) + 'px';
			
			active_select = _elem;
			if(document.documentElement)
			{
				document.documentElement.onclick = hideSelectOptions;
			}
			else
			{
				window.onclick = hideSelectOptions;
			}
			//_elem.keypress(optionKeyEvent);
			$(document).keypress(optionKeyPressEvent);
			$(document).keydown(optionKeyPressEvent);
			$(document).keyup(optionKeyUpEvent);
		}
		else if(_elem.className.indexOf("optionsDivVisible") != -1) {
			_elem.style.height = "auto";
			_elem.className = _elem.className.replace('optionsDivVisible','');
			_elem.className += " optionsDivInvisible";
		}
		
		// for mouseout
		/*_elem.timer = false;
		_elem.onmouseover = function() {
			if (this.timer) clearTimeout(this.timer);
		}
		_elem.onmouseout = function() {
			var _this = this;
			this.timer = setTimeout(function(){
				_this.style.height = "auto";
				_this.className = _this.className.replace('optionsDivVisible','');
				if (_elem.className.indexOf('optionsDivInvisible') == -1)
					_this.className += " optionsDivInvisible";
			},200);
		}*/
}

function hideSelectOptions(e)
{
	if(active_select)
	{
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(isElementBefore(_target,'selectArea') == 0 && isElementBefore(_target,'optionsDiv') == 0)
		{
			active_select.className = active_select.className.replace('optionsDivVisible', '');
			active_select.className = active_select.className.replace('optionsDivInvisible', '');
			active_select.className += " optionsDivInvisible";
			active_select = false;

			if(document.documentElement)
			{
				document.documentElement.onclick = function(){};
			}
			else
			{
				window.onclick = null;
			}
		}
		$(document).unbind('mouseup',confirmSelectFunction)
		$(document).unbind('keypress',optionKeyPressEvent);
		$(document).unbind('keydown',optionKeyPressEvent);
		$(document).unbind('keyup',optionKeyUpEvent);
	}
}

function isElementBefore(_el,_class)
{
	var _parent = _el;	
	do
	{
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	
	if(_parent.className && _parent.className.indexOf(_class) != -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

//greeting
function showGreetingMsg(){
	var trigger = $('#srcCodeGreetingMsg #searchlink');
	var greetingContent = $('#srcCodeGreetingMsg #subcontent');
	if(trigger.length > 0 && greetingContent.length >0){		
		trigger.mouseover(function(){
		var position = trigger.position();
		//var parentOffset = $('.wrapper_center').offset();
		//var width = greetingContent.width();
		//var height = greetingContent.height();
		greetingContent.css('left',position.left+trigger.outerWidth()-greetingContent.outerWidth());greetingContent.css('top',position.top+trigger.height());greetingContent.css('visibility','visible');});
		trigger.mouseout(function(){greetingContent.css('visibility','hidden');});
	}
}

//wish list and cart item number in header, cart item number is disable for now
function getAccountInfo(){

    $.ajax({
        type: "POST",
        url: "/getAccountInfo.jsp",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('useraccount').each(function(){
            	/*
                 $(this).find('shoppingcart').each(function(){   
                    var id_items=$(this).find('items').each(function(){
                        var cartQuan = $(this).find('quantity').text();
                        $("#cartSize").text(cartQuan);
                    
                    });        
                  }); 
                  */
                 $(this).find('wishlist').each(function(){   
                    var id_items=$(this).find('items').each(function(){
                        var wishListQuan = $(this).find('quantity').text();
                        $("#wishListSize").text(wishListQuan);
                    
                    });        
                  });                  
            });                  
         }
     }); 
}

//change search box back ground color
function changeSearchBoxBackground(){
	var searchBox = $('#ice_search');
	var defaultText = searchBox.attr('value');
	var focusClass = 'focus';
	searchBox.focus(function(){
	if(defaultText == this.value) this.value = "";
	this.className += " " + focusClass;
	this.parentNode.className += " parent-" + focusClass;});

	searchBox.blur(function(){
	if(this.value == "") {this.value = defaultText;}	
	this.className = this.className.replace(focusClass, "");
	this.parentNode.className = this.parentNode.className.replace("parent-"+focusClass, "");});

}

//option event
var oldIndex = 0;
var optionKeyUpEvent = function optionKeyUpEvent(e){
	if(active_select){
		var _activeSelect = $(active_select);
		var keyCode = -1;
		if(!e){
			e = window.event;			
		}
		
		if (e.keyCode){
			keyCode = e.keyCode;
		}else if (e.which){
			keyCode = e.which;
		}
		
		var index = 0;
		
		if(_activeSelect.attr("selectedIndex") != undefined){
			index =parseInt(_activeSelect.attr("selectedIndex"));
			oldIndex = index;
		}
		
		//if(keyCode >= 13){
		var alphabetText = /[a-zA-Z]/;
		var enteredChar = String.fromCharCode(keyCode);
        //return re.test(keyChar); 
		var keyStatus = -1;
		if(alphabetText.test(enteredChar)){//keyCode >= 65 && keyCode <=90){//alphabet
			keyStatus = 0;
		}else if(keyCode == 38){//up
			keyStatus = 1;
		}else if(keyCode == 40){//down
			keyStatus = 2;
		}else if(keyCode == 13){//enter
			keyStatus = 3;
		}else if(keyCode == 9  ){//tab	
			if(isTabOpen){
				isTabOpen = false;
			}else{
				keyStatus = 3;
			}
			
		}
		if(keyStatus != -1){
			var options = $('ul li a',_activeSelect);
			switch(keyStatus){
				case 0:
		    		for(var i=0;i<options.length;i++){
		    			var currentIndex = (1+oldIndex+i)%(options.length);
		    			var option = $(options[currentIndex]);
		    			var optionText = option.text();
		    			if(optionText.substring(0,1).toUpperCase() == enteredChar.toUpperCase()){
							setSelectedOption(_activeSelect,options,currentIndex,oldIndex);
							break;
		    			}
		    		}
					break;
				case 1:
					if(index > 0){
						setSelectedOption(_activeSelect,options,index-1,oldIndex);
					}
					break;
				case 2:
					if(index < (options.length-1)){
						setSelectedOption(_activeSelect,options,index+1,oldIndex);
					}
					break;
				case 3:
					//$(options[index]).click();
					var jsFunction = $(options[index]).attr('href');
					eval(jsFunction);
					$(document).unbind('mouseup',confirmSelectFunction)
					//$(document).unbind('keypress',optionKeyEvent);
					$(document).unbind('keypress',optionKeyPressEvent);
					$(document).unbind('keydown',optionKeyPressEvent);
					$(document).unbind('keyup',optionKeyUpEvent);
					$(document).unbind('click');
					break;
				default:
					break;
			}
		}
	}
	return false;
}

var optionKeyPressEvent = function(e){
	if(!e){
		e = window.event;			
	}
	e.preventDefault();
	return false;
}

var confirmSelectFunction = function(event){
	if(active_select){
		var _activeSelect = $(active_select);
		if(_activeSelect.attr("selectedIndex") != undefined){
			index = _activeSelect.attr("selectedIndex");
		}
		var options = $('ul li a',_activeSelect);
		var option = $(options[index]);
		var link1 = $(option).attr('href');
		var link2 = $(event.target).attr('href');
		if(option && (link1 != link2)){
			var jsFunction = option.attr('href');
			eval(jsFunction);
		}
	}
}

function setSelectedOption(openedSelect, options,index,oldIndex){
	openedSelect.attr("selectedIndex",index);
	var option = $(options[index]);
	var dropDownHeight = openedSelect.height();	
	var offsetHeight = option.parent().position().top+option.outerHeight();
	//if(index >= 52){//No. 52 'Armed Forces Americas' takes two lines
	//	offsetHeight = (index+2)*option.outerHeight();
	//}else{
	//	offsetHeight = (index+1)*option.outerHeight();
	//}
	 
	var diff = offsetHeight - dropDownHeight;
	//if(diff > 0){
		//var ulElment = $('ul',openedSelect);
		//ulElment.css('margin-top',diff);
		openedSelect.scrollTop(diff);
	//}
	$(options[oldIndex]).css('background-color','#ffffff')
	option.css('background-color','#e5e5e5');
/*	if(document.documentElement)
	{
		document.documentElement.onclick = function(){option.click()};
	}
	else
	{
		window.onclick = function(){option.click()};
	}*/
	$(document).mouseup(confirmSelectFunction);
}

var isMouseEvent = false;
var selectTabMouseHandler = function(){
	isMouseEvent = true;
}

var isTabOpen = false;
var selectTabFocusHandler = function(e){
	if(!e){
		e = window.event;			
	}
	
	//if(e.hasOwnProperty('originalEvent')){
	if(!isMouseEvent){
		isTabOpen = true;
		var openSelectDiv = $(this).attr('href');
		eval(openSelectDiv);
	}else{
		isMouseEvent = false;
	}				
}
// sine page ==> validating the email fild for the forgot password form 

$(document).ready(function() { 

    $('#newcomssin').click(function() {  
 
        $(".error").remove();
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        var emailaddressVal = $("#reminder_email").val();
        if(emailaddressVal == '') {
            $("#reminder_email").after('<style type="text/css">#reminderemailerror{display:block;}#reminder_email{border:1px solid #FF0101;} </style>');
			document.getElementById("reminderemailerror").innerHTML = 'Please enter your email address.';  
            hasError = true;
        }

        else if(!emailReg.test(emailaddressVal)) {
		   			document.getElementById("reminderemailerror").innerHTML = 'Enter a valid email address.';
            hasError = true;
        }

        if(hasError == true) { return false; }

    });
});
 
