Array.prototype.unique = function() {
	var a = [];
	var l = this.length;
	for(var i = 0; i < l; i++) {
		for(var j = i+1; j < l; j++) {
			if (this[i] === this[j])
				j = ++i;
		}
		a.push(this[i]);
	}
	return a;
};

isInteger = function( s ) {
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}
Array.prototype.union = function(list, callback)
{
        if ( 'function' != typeof callback ) {
                callback = function(value1, value2)
                {
                        return value1 != value2;
                }
        }

        var result = this;
        var L = result.length;
        var j;
        var u;
        for (var i = 0; i < list.length; i++) {
                j = 0;
                u = true;
                while ( j < L ) {
                        u = callback(result[j], list[i]);
                        if ( ! u ) {
                                break;
                        }
                        j++;
                }
                if ( ! u ) {
                        continue;
                }

                result[L] = list[i];
                L++;
        }
        return result;
}
Array.prototype.copy = function() {
	return [].concat(this);
};



$(document).ready(function() {

	var account_dd = $('#account_dd');
	var account_toggler = $('#account_toggler');
	var page_link = $('#account_toggler .page_link');
	account_toggler.css('visibility', 'visible')
	account_toggler.hover(function() {
		if ( page_link.hasClass('dropped') ) {
			account_dd.hide();
			page_link.removeClass('dropped');
		}
		else {
			account_dd.show();
			page_link.addClass('dropped');
		}
		return false;
	});



	$('.cartparam').find('.block_inp').val('');
	window.alert = function(text, title, callback) {
		alertBlock = $('<div title="' + (title ? title : 'Message') + '"><p>' + text + '</p></div>');
		$('body').append(alertBlock);
		alertBlock.dialog({
			modal: true,
			autoOpen: false,
			close: function(event, ui){
				if($.isFunction(callback)) callback();
				$(this).remove();
			},
			buttons: {
				Ok: function() {
					$(this).dialog( "close" );
				}
			}
		});
		alertBlock.dialog('open');
	}
	//$('.stylish_select').sSelect();
	$(".get_notified").colorbox({
		close: "Close",
		maxWidth:"550px",
		onComplete: function(){
			$('#get_notified').validate({
				rules: {
					your_email: {
						required: true,
						email: true
					}
				},
				messages: {
					your_email: {
						required: "Your Email must be not empty",
						email: "Invalid Your Email format"
					}
				},
				showErrors: function(errorMap, errorList) {
					this.defaultShowErrors();
					$.colorbox.resize({height:($('#ajax').height() + 90) });
				},
				onclick: false,
				onkeyup: false,
				onfocusout: false,
				errorContainer: '#get_notified .msg',
				errorLabelContainer: "#get_notified .msg .messenger_ul_error",
				wrapper: "li",
				submitHandler: function(form) {
					jQuery(form).ajaxSubmit({
						dataType: 'json',
						success: function(res, statusText, xhr, $form){
							if(res == 'OK'){
								alert('Thank you for your request. As soon as the product becomes available, we will notify you via email.');
								$.colorbox.close();
							} else {
								if(res.errors.length){
									errors = '';

									for(i=0; i<res.errors.length; i++){
										errors = errors + '<li>' + res.errors[i] + '</li>'
									}
									$("#get_notified .msg").attr('style', '')
									$("#get_notified .msg .messenger_ul_error").attr('style', '').html(errors);
								} else {
									$.colorbox.close();
									alert(res.msg);
								}
							}
						}
					});
				}
			});

			$('#get_notified .block .button.ebutton.black').live('click', function(e){
				$(this).parents('.block').find('input').val($(this).attr('option_value'));
				$(this).parents('.block').find('.ebutton').removeClass('black').addClass('gray');
				$(this).removeClass('gray').addClass('red');
				e.preventDefault();
			});
			$('#get_notified .block .button.ebutton.red').live('click', function(e){
				$(this).parents('.block').find('input').val('');
				$(this).parents('.block').find('.ebutton').removeClass('red').removeClass('gray').addClass('black');
				e.preventDefault();
			});
			$('#get_notified .block .button.ebutton.color.available').live('click', function(e){
				$(this).parents('.block').find('input').val($(this).attr('option_value'));
				$(this).parents('.block').find('.ebutton').removeClass('selected').addClass('available');
				$(this).removeClass('available').addClass('selected');
				e.preventDefault();
			});
			$('#get_notified .block .button.ebutton.color.selected').live('click', function(e){
				$(this).parents('.block').find('input').val('');
				$(this).parents('.block').find('.ebutton').removeClass('selected').addClass('available');
				e.preventDefault();
			});

			$('#get_notified .block .button.ebutton.gray').live('click', function(e){
				e.preventDefault();
			});

			$('#get_notified .block .button.ebutton.color').each(function(){
				$(this).css('background-color', $(this).attr('option_value'));
			});

			$('#get_notified input:submit').live('click',function(event){
				cond=true;
				for(i=0;i<$('#get_notified .block').length;i++){
					if($('#get_notified .block').eq(i).find('input').val().length==0) cond=false;
				}
				if(!cond){
					alert('Please choose all required options');
					event.preventDefault();
				}
				//event.preventDefault();
			});
		}
	});

	$(".popup").colorbox({
		close: "Close",
		innerWidth: "550px",
		scrolling:false
	});
	$("#form_product .popup").colorbox({
		close: "Close",
		innerWidth: "850px",
		scrolling:false
	});	
	$(".iframe").colorbox({
		close: "Close",
		width:"465px", height:"350px",
		iframe:true
	});
	$('.home_slider').animate({ opacity: 1 }, 800);

	$('.slider').each(function(){
		var interval ,speed, slider_name;
		slider_name = $(this).attr('id');
		switch ($(this).attr('id')) {
			case "home-slider" :
				interval = ($(this).children().length>1 ? 10000 : -1);
				speed = 2000;
				$.featureList(
					$('.'+ slider_name +'-nav a'),
					$(this).children(),
					{
						start_item          : 0,
						transition_interval : interval,
						transition_speed    : speed
					}
				);
			break;
			default :
				interval = -1;
				speed = 400;
				$.featureList2(
					$('.'+ slider_name +'-nav a'),
					$(this).children(),
					{
						start_item          : 0,
						transition_interval : interval,
						transition_speed    : speed
					}
				);
		}
	});



	$('.order_toggler').click(function() {

		var status = $(this).html();


		if (status == '+') {

			$(this).parent().find('.shopping_cart').show();
			$(this).text('-');
		}
		else {
			$(this).parent().find('.shopping_cart').hide();
			$(this).text('+');
		}
		return false;
	});

	var i=0;
	$('.icon.close').each(function(){
		var num = i++,
		elem = $(this);

		elem.bind('click', function(){
			$.ajax({
				cache: false,
				type : 'get',
				url : 'cartaction/delete',
				data: {'num': num},
				success : function(res){
					if(res==0){
						$('.shopping_cart.shopping_cart_table.products_list').hide(600).remove();
						$('#cart_buttons').hide(600);
						$('.shopping_cart.shopping_cart_table.empty').show(600);
					} else {
						elem.parents('.row').hide(600).remove();
						$('.shopping_cart.shopping_cart_table.products_list li').removeClass('odd');
						$('.shopping_cart.shopping_cart_table.products_list li:odd').addClass('odd');
					}
					$('#total').html('$ '+res);
				}
			});
		});
	});
	$('.inp_t.quant').bind('blur', function(){
		var elem = this;
		if(!isInteger($(this).val())) {
			alert('Invalid quantity', 'Message', function(){elem.focus()});
			$(this).val('');
		}
	});


	function showFormMessage(elform, err_arr){
		messageBlock = elform.parent().find('.message_block');
		if(messageBlock.length==0) {
			messageBlock.remove();
			messageBlock = $('<div></div>');
			messageBlock.css('padding-bottom', '14px');
			messageBlock.attr('class', 'message_block');
		}
		
		if(err_arr.length==0){
			messageBlock.css('color','#238401');
			messageBlock.html('Your message has been sent');
		} else {
			errorMessage='';
			for(i=0; i<err_arr.length; i++){
				errorMessage+='<div>' + err_arr[i] + '</div>';
			}
			messageBlock.css('color','#ff0000');
			messageBlock.html(errorMessage);
		}
		messageBlock.insertBefore(elform);
	}
	$('form.footersendform').bind({
		'mousemove': function(){
			$(this).find('input[name=phone]').val('human');
			$(this).attr('action', $(this).attr('mailer')).unbind('mousemove');
		},
		'submit': function(event){
			var elform = $(this),
			first_name = elform.find('input.first_name').val(),
			name = elform.find('input.name').val(),
			email = elform.find('input.email').val(),
			website = elform.find('input.website').val(),
			phone = elform.find('input.phone').val(),
			message = elform.find('textarea.message').val(),
			
			err_arr = [];
			if(name=='Name:'){
				name = '';
				err_arr[err_arr.length] = 'Name must be not empty';
			}
			if(email=='E-mail:'){
				email = '';
				err_arr[err_arr.length] = 'Email must be not empty';
			} else {
				if(!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email))){
					err_arr[err_arr.length] = 'Invalid Email format';
				}
			}
			if(website!='Website:' || phone!='human'){
				website = '';
				err_arr[err_arr.length] = 'Message not sent. Human`s test failed.';
			}
			if(message=='Message:'){
				message = '';
				err_arr[err_arr.length] = 'Message must be not empty';
			}
			if(err_arr.length==0){
				$.ajax({
					cache: false,
					type : 'post',
					url : elform.attr('action'),
					data: {
						'first_name': first_name,
						'name': name,
						'email': email,
						'website': website,
						'phone': phone,
						'message': message
					},
					success : function(resp){
						err_arr = eval(resp);
						//console.dir(err_arr);
						showFormMessage(elform, err_arr);
					}
				});
			} else {
				showFormMessage(elform, err_arr);
			}
			event.preventDefault();
		}
	});

	$('#form_register').each(function(){
		$(this).validate({
			rules: {
				lastname: "required",
				firstname: "required",
				password: {
					required: true,
					minlength: 5
				},
				password_confirm: {
					required: true,
					minlength: 5,
					equalTo: "#password"
				},
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				firstname: "Firstname must be not empty",
				lastname: "Lastname must be not empty",
				password: {
					required: "Password must be not empty",
					minlength: "Password should be at least 5 characters"
				},
				password_confirm: {
					required: "Confirm Password must be not empty",
					minlength: "Confirm Password should be at least 5 characters",
					equalTo: "Password confirm failed"
				},
				email: {
					required: "Email must be not empty",
					email: "Invalid Email format"
				}
			},
			errorContainer: '#messageBox',
			errorLabelContainer: "#messageBox .messenger_ul_error",
			wrapper: "li",
			invalidHandler: function(){$('#messageBox ul').html('');}
			//onfocusout: false,
			//focusInvalid: false,
			//focusCleanup: false
		});
	});
	function scrollTop(){
		$('html').scrollTo($('#messageBox'));
	}
	$('#shipping_billing_form').each(function(){
		if($('.addressblockwr').length==0){
			var form = $(this);
			form.validate({
				rules: {
					s_firstname: "required",
					s_lastname: "required",
					s_phone: "required",
					s_address: "required",
					s_city: "required",
					s_zip: "required",
					s_email: {
						required: true,
						email: true
					}
				},
				messages: {
					s_firstname: "Please enter Shipping First Name",
					s_lastname: "Please enter Shipping Last Name",
					s_phone: "Please enter Shipping Phone",
					s_address: "Please enter Shipping Address",
					s_city: "Please enter Shipping City",
					s_zip: "Please enter Shipping Zip Code",
					s_email: {
						required: "Please enter Shipping Email",
						email: "Invalid shipping Email"
					}
				},
				errorContainer: '#messageBox',
				errorLabelContainer: "#messageBox .messenger_ul_error",
				wrapper: "li",
				invalidHandler: function(){$('#messageBox ul').html('');window.setTimeout(scrollTop, 30);}
			});
			rulesSec = [
				[
					'b_firstname',
					{
						required: true,
						messages: {
							required: "Please enter Billing First Name"
						}
					}
				],
				[
					'b_lastname',
					{
						required: true,
						messages: {
							required: "Please enter Billing Last Name"
						}
					}
				],
				[
					'b_phone',
					{
						required: true,
						messages: {
							required: "Please enter Billing Phone"
						}
					}
				],
				[
					'b_address',
					{
						required: true,
						messages: {
							required: "Please enter Billing Address"
						}
					}
				],
				[
					'b_city',
					{
						required: true,
						messages: {
							required: "Please enter Billing City"
						}
					}
				],
				[
					'b_zip',
					{
						required: true,
						messages: {
							required: "Please enter Billing Zip"
						}
					}
				],
				[
					'b_email',
					{
						email: true,
						messages: {
							required: "Invalid billing Email"
						}
					}
				]
			];
			$('#equals_shipping').bind('change', function(){
				$('#equals_shipping_copy').attr('checked', $('#equals_shipping').attr('checked'));
				if($('#equals_shipping').attr('checked')){
					for(i=0;i<rulesSec.length;i++){
						currentRule = rulesSec[i];
						form.find('[name='+currentRule[0]+']').rules('remove');
					}
					$('.form.shop_cart.fl_r input[type=text]').attr('disabled', 'disabled');
					$('.form.shop_cart.fl_r select').attr('disabled', 'disabled');
				} else {
					for(i=0;i<rulesSec.length;i++){
						currentRule = rulesSec[i];
						form.find('[name='+currentRule[0]+']').removeAttr('disabled').rules('add', currentRule[1]);
					}
					$('.form.shop_cart.fl_r input[type=text]').removeAttr('disabled');
					$('.form.shop_cart.fl_r select').removeAttr('disabled');
				}
			});
			$('#equals_shipping').triggerHandler('change');
			$('#equals_shipping_copy').bind('click', function(){
				$('#equals_shipping').attr('checked', $('#equals_shipping_copy').attr('checked'));
				if($('#equals_shipping_copy').attr('checked')){
					for(i=0;i<rulesSec.length;i++){
						currentRule = rulesSec[i];
						form.find('[name='+currentRule[0]+']').rules('remove');
					}
					$('.form.shop_cart.fl_r input[type=text]').attr('disabled', 'disabled');
					$('.form.shop_cart.fl_r select').attr('disabled', 'disabled');
				} else {
					for(i=0;i<rulesSec.length;i++){
						currentRule = rulesSec[i];
						form.find('[name='+currentRule[0]+']').removeAttr('disabled').rules('add', currentRule[1]);
					}
					$('.form.shop_cart.fl_r input[type=text]').removeAttr('disabled');
					$('.form.shop_cart.fl_r select').removeAttr('disabled');
				}
			});

			/*
			function copyFieldVal(){
				if($('#equals_shipping').attr('checked')){
					form.find('input[id^=s_]').each(function(){
						form.find('input[id=b_' + $(this).attr('id').replace('s_', '') + ']').val($(this).val());
					});
					form.find('select[id^=s_]').each(function(){
						form.find('select[id=b_' + $(this).attr('id').replace('s_', '') + ']').attr('selectedIndex', $(this).attr('selectedIndex'));
					});
				}
			}

			$('#equals_shipping').bind('change', function(){
				if($('#equals_shipping').attr('checked')){
					form.find('input').bind('change.copyFieldVal', copyFieldVal);
					form.find('select').bind('change.copyFieldVal', copyFieldVal);
					copyFieldVal()
				} else {
					form.find('input').unbind('change.copyFieldVal');
					form.find('select').unbind('change.copyFieldVal');
				}
			});

			$('#equals_shipping_copy').click(function(){
				if ($(this).is(':checked'))
				{
					$('#equals_shipping').attr('checked', true);
				}
				else
				{
					$('#equals_shipping').attr('checked', false);
				}
			});
			$('#equals_shipping').click(function(){
				if ($(this).is(':checked'))
				{
					$('#equals_shipping_copy').attr('checked', true);
				}
				else
				{
					$('#equals_shipping_copy').attr('checked', false);
				}
			});*/
		}
	});
	$('#cartForm').each(function(){
		$(this).find('input.btnupdate').bind('click', function(e){
			$(this).parents('form').find('input[name=shop_action]').val('update');
			$(this).parents('form').submit();
			e.preventDefault();
		});
		$(this).find('input.btncheckout').bind('click', function(e){
			$(this).parents('form').find('input[name=shop_action]').val('checkout');
			$(this).parents('form').submit();
			e.preventDefault();
		});
	});
	$('#applyButton').bind('click', function(){
		$('#code_apply').val('1');
		$(this).parents('form').trigger('submit');
	});
	$('#pay_with').each(function(){
		var submitButton = $(this).parents('form').find('input[type=submit]'),
		submitButtonValue = submitButton.val();
		submitButton.css({
			width:(submitButton.width()+38)+'px'
		})
		function pay_with_paypal(event){
			event.preventDefault();
			$.ajax({
				cache: false,
				type: "POST",
				url: $('#save_online_order_url').val(),
				data: {},
				success: function(r){
					if(r != '0'){
						$('#invoice').val(r);
						$('.paypal_form').trigger('submit');
					}
                    else{
                        alert('ORDER ERROR');
                    }
				}
			});
		}
		$(this).bind('change', function(){
			if($(this).val()=='paypal'){
				$('#pay_with_card').fadeOut();
				//submitButton.val('Pay with Paypal &raquo;').bind('click.payPal', pay_with_paypal).fadeIn();

				submitButton.val('Pay with Paypal ' + String.fromCharCode(187) ).bind('click.payPal', pay_with_paypal);
				submitButton.removeAttr('disabled');
				submitButton.removeClass('gray');
				submitButton.addClass('red');
			} else if($(this).val()==0) {
				//submitButton.fadeOut();

				$('#pay_with_card').fadeOut();
				submitButton.attr('disabled', 'disabled');
				submitButton.addClass('gray');
				submitButton.removeClass('red');
			} else {
				$('#pay_with_card').fadeIn();

				submitButton.val(submitButtonValue).unbind('click.payPal');
				submitButton.removeAttr('disabled');
				submitButton.removeClass('gray');
				submitButton.addClass('red');
			}
		});
		$(this).triggerHandler('change');
	});

	/*
		Function that makes user meta fields
		where
		.editable_field - container
		.form_el - form element
		.value_el - element, containing the value
	*/

	$('form.editable_form').each(function(){

		var toggler = $(this).find('a.edit');
		var save_btn = $(this).find('input.button');

		toggler.click(function(){
			toggle_save_btn(save_btn);
		});

		/*
		save_btn.click(function(){
			toggle_save_btn(save_btn);
		});
		*/

		// Apply functions to all editable fields
		$(this).find('.editable_field').each(function(){

			var form_el = $(this).find('.form_el');   // form elements
			var value_el = $(this).find('.value_el'); // elements containin values


			// Aplying toggler functional
			toggler.click(function(){
				toggle_editable(form_el, value_el);
				return false;
			});

			/*
			// Applying save button functional
			save_btn.click(function(){
				if (form_el.get(0).tagName == 'SELECT') {
					value_el.html(form_el.children(':selected').html());
				}
				else {
					value_el.html(form_el.val());
				}
				toggle_editable(form_el, value_el);
				return false;
			});
			*/
		}); // On each .editable field
	}); // On each form on the page

	$(".options .ebutton").tooltip({
		delay: 0,
		showURL: false,
		bodyHandler: function() {
			return $(this).attr("title1");
		}
	});


}); // Document Ready Function

/*
	Functions Used by editable fields
	toggle_editable - toogles editable elems
	toggle_save_btn - toggles save buttons
*/

function toggle_editable(form_el, value_el) {
	form_el.toggle();
	value_el.toggle();
};
function toggle_save_btn(save_btn) {
	save_btn.toggle();
}

$(document).ready(function(){
	$('#signinrequest a').each(function(){
		$(this).click(function(e){
			$(this).parent().hide();
			$('#signinform').show();
			e.preventDefault();
		});
	});
	var colorboxparam = {
		inline:true,
		href:"#addressform",
		speed:100
	},
	fields = [
		'firstname',
		'lastname',
		'email',
		'phone',
		'company',
		'address',
		'address_2',
		'city',
		'country',
		'state',
		'zip'
	];
	$('#shiping-address').each(function(){
		var wr = $(this);
		wr.find('.edit').bind('click', function(e){
			//wr.find('input').val('');
			wr.hide()
			$('#shiping-form-hidden').show()
			e.preventDefault();
		});
		$('#moreaddressform').each(function(){
			var url = $('#moreaddressform').find('form').get(0).action;
			$('#moreaddressform .address-block').click(function(){
				$('#moreaddressform a').attr('href', url+'/'+$(this).find('input[type=radio]').val()+'?ref='+$('#moreaddressform input[name=ref]').val());
				$(this).find('input[type=radio]').attr('checked', 'checked');
			});
			$('#moreaddressform .new').click(function(e){
				for(i=0;i<fields.length;i++){
					if(fields[i]!='state' && fields[i]!='country'){
						$('#shipping_billing_form input[name=s_'+fields[i]+']').val('')
					} else {
						$('#shipping_billing_form select[name=s_'+fields[i]+'] option').eq(0).attr('selected', 'selected');
					}
				}
				wr.find('input').val('');
				$.colorbox.close();
				wr.find('.edit').triggerHandler('click')
				e.preventDefault();
			});
			if($('#moreaddressform').find('.address-block').length>1){

				wr.find('.select').bind('click', function(e){
					$.colorbox($.extend(colorboxparam, {
						href : "#moreaddressform"
					}));
					e.preventDefault();
				});
			} else {
				wr.find('.select').bind('click', function(e){
					for(i=0;i<fields.length;i++){
						if(fields[i]!='state' && fields[i]!='country'){
							$('#shipping_billing_form input[name=s_'+fields[i]+']').val('')
						} else {
							$('#shipping_billing_form select[name=s_'+fields[i]+'] option').eq(0).attr('selected', 'selected');
						}
					}
					wr.find('input').val('');
					wr.find('.edit').triggerHandler('click')
					e.preventDefault();
				});
				wr.find('.select').text('Add new shiping address');
			}		
		});
	});
	$('#billing-address').each(function(){
		var wr = $(this);
		wr.find('.edit').bind('click', function(e){
			//wr.find('input').val('');
			wr.hide()
			$('#billing-form-hidden').show()
			e.preventDefault();
		});
	});
	$('.dropdown .link_list').each(function(){
		$('#account_dd').css('width', $('#account_toggler').width()-10);
		$(this).css('padding-left', '7px');
	});
	$('#b_country').each(function(){
		var states = [
			$('#b_state optgroup').eq(1).find('option').clone(),
			$('#b_state optgroup').eq(0).find('option').clone()
		]
		$('#b_country').change(function(){
			$('#b_state').html('');
			$('#b_state').append(states[$(this).find('option').index($(this).find(':selected').get(0))].clone());
		}).triggerHandler('change');
	});
	$('#s_country').each(function(){
		var states = [
			$('#s_state optgroup').eq(1).find('option').clone(),
			$('#s_state optgroup').eq(0).find('option').clone()
		]
		$('#s_country').change(function(){
			$('#s_state').html('');
			$('#s_state').append(states[$(this).find('option').index($(this).find(':selected').get(0))].clone());
		}).triggerHandler('change');
		
	});
});


