
function show_size_chart(){
	$('size-chart').show();
}

function show_madison_popup(){
	$('madison_popup').show();
}
function popup_close(){
	$('madison_popup').hide();
}

function submit_email_to_madison_form(servlet_path) {
	var first_name = jQuery("form#email_to_madison input[name='FirstName']").val();
	var last_name = jQuery("form#email_to_madison input[name='LastName']").val();	
	var phone = jQuery("form#email_to_madison input[name='phone']").val();
	var email = jQuery("form#email_to_madison input[name='email']").val();
	var style_number = jQuery("form#email_to_madison input[name='styleNumber']").val();
	var size = jQuery("form#email_to_madison input[name='size']").val();
	var color = jQuery("form#email_to_madison input[name='color']").val();
	
	if(validateField() == false) {
		return;
	}
	
	new Ajax.Request(servlet_path, {
		method : 'post',
		parameters : {
			randid : Math.random()
		},
		onSuccess : function(transport) {
			$('modal-dialog_content').innerHTML = transport.responseText;
			
			if (transport.getHeader('ACDC_ERROR') == 't') {
				//show_madison_popup();
			} else {
				var order = new Object();
				order['first_name'] = first_name;
				order['last_name'] = last_name;
				order['phone'] = phone;
				order['email'] = email;
				order['style_number'] = style_number;
				order['size'] = size;
				order['color'] = color;				
				
				(new MarinTracking()).track(order);
			}
		},
		postBody : get_form_values('email_to_madison')
	});	
	popup_close();
	document.getElementById("madison_click").style.display = 'none';
	
}


function validateField() {
		refreshField();
        var validate = true;
        if(document.getElementById('FirstName').value == ""){                
                document.getElementById('fname_error').style.display = 'block';
                validate = false;
        }if(document.getElementById('LastName').value == ""){
                document.getElementById('lname_error').style.display = 'block';
                validate = false;
        }if(document.getElementById('phone_number').value == ""){
                document.getElementById('phone_error').style.display = 'block';
                validate = false;
        }if(document.getElementById('email').value == ""){
                document.getElementById('email_error').style.display = 'block';
                validate = false;
        }if(document.getElementById('size').value == ""){
                document.getElementById('size_error').style.display = 'block';
                validate = false;
        }if(document.getElementById('color').value == ""){
                document.getElementById('color_error').style.display = 'block';
                validate = false;
        }
        return validate;
}


function refreshField() {
		document.getElementById('fname_error').style.display = 'none';
        document.getElementById('lname_error').style.display = 'none';
        document.getElementById('phone_error').style.display = 'none';
        document.getElementById('email_error').style.display = 'none';
        document.getElementById('size_error').style.display = 'none';
        document.getElementById('color_error').style.display = 'none';       
}





function show_size_chart_children(){
	$('size-chart-children').show();
}

function show_add_to_cart_section(context, json_page, product_id) {
	var json_sku_info = '';

	/* Grab the latest state of infomation for the skus as a JSON string */
    new Ajax.Request(json_page, {
            method: 'get',
            parameters: {product_id: product_id},
            onSuccess: function(transport) {
                    json_sku_info = transport.responseJSON;
                    //alert(json_sku_info);
					
					/* Maintain state based on the sku info in the JSON string */
					if(json_sku_info.length == 1){
						/* If there's only 1 sku, we don't need to use the smart dropdown logic */
						if(json_sku_info[0].INSTOCK != 'true'){
							jQuery('#color_select').find('option').remove();
                            jQuery('#size_select').find('option').remove();
							
							/* If it's out of stock, we show the out of stock button and banner */
							$('in_stock_span').hide();
							$('out_of_stock_span').show();
							$('submit_link').onclick = '';
							
							$('button_in_stock_span').hide();
							$('button_out_of_stock_span').show();
							if(json_sku_info[0].COLOR != null){
                                  $('color_span').style.display = '';
                                  jQuery('#color_select').append(jQuery("<option></option>").attr("value",json_sku_info[0].COLOR_ID).text(json_sku_info[0].COLOR));
                            }
                            if(json_sku_info[0].SIZE != null){
                                  $('size_span').style.display = '';
                                 jQuery('#size_select').append(jQuery("<option></option>").attr("value",json_sku_info[0].SIZE_ID).text(json_sku_info[0].SIZE + json_sku_info[0].DROPDOWN_PRICE));
                            }							
						}else{		
							/* We don't need to expose the dropdowns, just quietly populate the dropdown with the designated
							values and marked them as the selected options */
							jQuery('#color_select').find('option').remove();
                            jQuery('#size_select').find('option').remove();
							$('in_stock_span').show();
							$('out_of_stock_span').hide();							
							$('button_in_stock_span').show();
							$('button_out_of_stock_span').hide();
							
							if(json_sku_info[0].COLOR != null){		
								$('color_span').style.display = '';						
								jQuery('#color_select').append(jQuery("<option></option>").attr("value",json_sku_info[0].COLOR_ID).text(json_sku_info[0].COLOR));
							}
							if(json_sku_info[0].SIZE != null){
								$('size_span').style.display = '';
                                jQuery('#size_select').append(jQuery("<option></option>").attr("value",json_sku_info[0].SIZE_ID).text(json_sku_info[0].SIZE + json_sku_info[0].DROPDOWN_PRICE));
							}
						}
					}else{
						/* smart dropdown logic */
						//$('color_select').onchange = function(){handle_sku_states(json_sku_info, context)};	
						//$('size_select').onchange = function(){handle_sku_states(json_sku_info, context)};
						handle_initial_dropdowns(json_sku_info, context);
						
						jQuery('#color_select').change(
							function(objEvent) {
								alert('some change the color');
								handle_sku_states(json_sku_info, context);
							}
						);
						jQuery('#size_select').change(
							function(objEvent) {
								handle_sku_states(json_sku_info, context);
							}
						);
					}
                    
                                        
                	/* Expose shopping cart form */
					$('product_add_to_cart_div').style.display = '';
					
					/* re-render the dropdowns with the styled look-n-feel */
					if (!(jQuery.browser.msie && jQuery.browser.version < 7)) {
						jQuery("select").selectbox();
						
						//need to re-bind the onChange event.
						jQuery('#color_select').change(
							function(objEvent) {
								handle_sku_states(json_sku_info, context);
							}
						);
						jQuery('#size_select').change(
							function(objEvent) {
								handle_sku_states(json_sku_info, context);
							}
						);
					}
					
					/* For non IE browsers, we have to manually align the qty field with the dropdowns since jNice dropdowns play by their own rules... */
					if (!jQuery.browser.msie){
						$('quantity').style.marginTop = '-6px';
					}
					
					gaTrackingOOSEvent();
      		}
    });
}

/* Enables/disables the add to cart functionality based on the inventory of the selected color/size combo */
function handle_sku_states(json_string, context){
	var color_selected_index = $('color_select').options.selectedIndex;
	var size_selected_index = $('size_select').options.selectedIndex;
	var color_selected_value = $('color_select').options[$('color_select').options.selectedIndex].value; 
	var size_selected_value = $('size_select').options[$('size_select').options.selectedIndex].value;
	var color_selected_text = $('color_select').options[$('color_select').options.selectedIndex].text; 
	var size_selected_text = $('size_select').options[$('size_select').options.selectedIndex].text;

	/* Tells zoomify player to update images to newly selected color */	
	selectVariation(color_selected_text);
		
		
    /* Make sure all selectable options are selected before showing/hiding the in-stock/out-of-stock msgs */
     if(color_selected_index == 0 || size_selected_index == 0){
         for(var x = 0; x < json_string.length; x++){
              var color_value = json_string[x].COLOR;
              var size_value = json_string[x].SIZE + json_string[x].DROPDOWN_PRICE;

              if(color_value == color_selected_text && size_value == size_selected_text){
              		if(json_string[x].PRICE != ''){
              			$('saleprice').innerHTML = json_string[x].PRICE;
              		}
              
                	if(json_string[x].INSTOCK == "true") {
                        //$('in_stock_span').show();
                        //$('out_of_stock_span').hide();
                        //$('add_to_cart_span').show();

                        $('button_in_stock_span').show();
                        $('button_out_of_stock_span').hide();
                        $('button_add_to_cart_span').show();                        
                	} else {
                        $('button_in_stock_span').hide();
                        $('button_out_of_stock_span').show();
                        $('button_add_to_cart_span').hide();
                	}
              }
        }
    }else{

		var foundMatchedSku = false;
		for(var x = 0; x < json_string.length; x++){
			var color_value = json_string[x].COLOR;			
			var size_value = json_string[x].SIZE + json_string[x].DROPDOWN_PRICE;
							
			if(color_value == color_selected_text && size_value == size_selected_text){
				if(json_string[x].PRICE != ''){
					$('saleprice').innerHTML = json_string[x].PRICE;
				}
				
				if(json_string[x].INSTOCK == "true"){
					$('in_stock_span').show();
					$('out_of_stock_span').hide();
					//$('add_to_cart_span').show();
					
					$('button_in_stock_span').show();
					$('button_out_of_stock_span').hide();
					$('button_add_to_cart_span').show();
				}else{
					$('in_stock_span').hide();	
					$('out_of_stock_span').show();		
					//$('add_to_cart_span').hide();
					
					$('button_in_stock_span').hide();	
					$('button_out_of_stock_span').show();		
					$('button_add_to_cart_span').show();
				}
				foundMatchedSku = true;
			}
		}
	
	
		/* It's	possible the selected color/size combination points to a SKU that's pending. Hence this logic below */
		if(!foundMatchedSku){
			$('in_stock_span').hide();
			$('out_of_stock_span').show();	
			//$('add_to_cart_span').hide();	
			
			$('button_in_stock_span').hide();
			$('button_out_of_stock_span').show();	
			$('button_add_to_cart_span').hide();			
		}
	}
     
     gaTrackingOOSEvent();
}

/* Initilizes the content the of the dropdowns via a JSON_string */
function handle_initial_dropdowns(json_string, context){
	var color_group = {};
	var size_group = {};
	var sorted_color_options = new Array();
	var sorted_size_options = new Array();

	
	var color_counter = 0;
	var size_counter = 0;
	var needs_sorting = false;
	for(var x = 0; x < json_string.length; x++){
		var color_value = json_string[x].COLOR;
		var size_value = json_string[x].SIZE;

		/* Make sure color dropdown exists, color option isn't already in dropdown, and color dropdown wasn't preselected */
		if(color_value != null && color_group[color_value] == null){
			$('color_span').style.display = '';
			needs_sorting = true;
			color_group[color_value] = '1';
			var opt = document.createElement('option');
			opt.text = json_string[x].COLOR;
			//if(json_string[x].INSTOCK == 'true'){					
			//	at_least_one_in_stock = 'true';
			//}
			opt.value = json_string[x].COLOR_ID;
			sorted_color_options[color_counter] = new Array(2);
			sorted_color_options[color_counter][0] = json_string[x].COLOR_PRIORITY;
			sorted_color_options[color_counter++][1] = opt;
					
		}
		if(size_value != null && size_group[size_value] == null){
			$('size_span').style.display = '';
			needs_sorting = true;
			size_group[size_value] = '1';
			var opt = document.createElement('option');
			opt.text = json_string[x].SIZE;
			opt.price = json_string[x].DROPDOWN_PRICE;
			//if(json_string[x].INSTOCK == 'true'){
			//	at_least_one_in_stock = 'true';
			//}
			opt.value = json_string[x].SIZE_ID;
			sorted_size_options[size_counter] = new Array(2);
			sorted_size_options[size_counter][0] = json_string[x].SIZE_PRIORITY;
			sorted_size_options[size_counter++][1] = opt;
		}
	}
		
	if(needs_sorting){
		sorted_color_options.sort(sort_sku_options);
		sorted_size_options.sort(sort_sku_options);
		
		for(var a = 0; a < sorted_color_options.length; a++){
			//$('color_select').options.add(sorted_color_options[a][1]);
			jQuery('#color_select').append(jQuery("<option></option>").attr("value",sorted_color_options[a][1].value).text(sorted_color_options[a][1].text));
		}
		for(var b = 0; b < sorted_size_options.length; b++){
			//$('size_select').options.add(sorted_size_options[b][1]);
			jQuery('#size_select').append(jQuery("<option></option>").attr("value",sorted_size_options[b][1].value).text(sorted_size_options[b][1].text + sorted_size_options[b][1].price));
		}
	}
	
	var preSelectedOptions = 0;
	
	if(sorted_color_options.length == 1){
		/* pre-select the only color */
		jQuery('#color_select option:nth-child(2)').attr('selected', 'selected');
		preSelectedOptions ++;
	}
	
	if(sorted_size_options.length == 1){
		/* pre-select the only size */
		jQuery('#size_select option:nth-child(2)').attr('selected', 'selected');
		preSelectedOptions ++;
	}
	
	if (preSelectedOptions == 2){
		/* if both color and size are selected */
		if (sorted_size_options[0][1].text == 'Out of Stock'){
			$('out_of_stock_span').show();							
			$('button_out_of_stock_span').show();
		}else{
			$('in_stock_span').show();
			$('button_in_stock_span').show();
		}
	}
}

function sort_sku_options(a,b){
	if (a[0] < b[0])return -1;
	if (a[0] > b[0])return 1;
	return 0 ;
}

function submit_checkout_form(context_path){
	// Validate customer has selected all necessary options
	
	var errorColor = "#d92349";
	var normalColor = "#8E8E8E";
	var colorLabel = "label_color";
	var sizelabel = "label_size";
	var topErrorMessage = "topErrorMessage";
	
	// Set the label color to normal
	$(colorLabel).style.color = normalColor;
	$(sizelabel).style.color = normalColor;
	
	//short term solution for ie7 bug.
	if($('size_select').options.length == 2)
        $('size_select').options.selectedIndex = 1;

	
	if ($('color_select').options[$('color_select').selectedIndex].value == 'select' ||
		$('size_select').options[$('size_select').selectedIndex].value == 'select')
	{
		$(colorLabel).style.color = errorColor;
		$(sizelabel).style.color = errorColor;
		$(topErrorMessage).update('Please select all options.');
		
		return false;
	}
	
	if ($('size_select').options[$('size_select').selectedIndex].text.indexOf('out of stock') >= 0)
	{
		$(sizelabel).style.color = errorColor;
		$(topErrorMessage).update('Option selected is out of stock.');
		return false;
	}
	
	if( $('quantity').value > 0 ){
		/* Quantity is hardcoded to 1 so this will always be true */
	}else{
		$(qtyLabel).style.color = errorColor;
		$(topErrorMessage).update('Please enter a quantity');
		return false;
	}
	
	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/servlet/Cart', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML = '<strong>Your item cannot be added to cart.</strong>';
			} else {			
				//show mini shopping cart here
				//ajax to get content, params: product_id,option_params,qty
				//jsp page to get sku
				new Ajax.Request(context_path + '/shopping_cart/ajax/mini_cart.jsp',
						  {
						    method:'get',
						    parameters: get_form_values('checkout_form')+'&'+'randid='+Math.random(),
						    onSuccess: function(transport){
								
								$('shopping-cart').innerHTML = transport.responseText;
								
								//show shopping-cart
								if($('shopping-cart').style.display == 'none'){
									toggleMiniCart();
									
									//close mini cart after 5 seconds
									setTimeout("closeMiniCart()",5000);
								}
								
						    },
						    onFailure: function(){  }
						  });
				
				
				// Upon success we display a message as well as update the numItems count in the header 
				//$('checkout_message').style.display = '';
				 //$('checkout_message').innerHTML = '<strong>Item has been added to your cart!</strong> <a href="' + context_path + '/agent/login?toshipping=true">Checkout</a>';
				new Ajax.Request(context_path + '/templates/ajax/numItems.jsp',
				  {
				    method:'get',
				    parameters: {randid: Math.random()},
				    onSuccess: function(transport){
				      $('numItems').innerHTML = transport.responseText;
				    },
				    onFailure: function(){  }
				  });
			}
		},
		postBody: get_form_values('checkout_form')
	});
	
	
}

//gift card checkout 
function submit_gift_card_checkout_form(context_path){
	// Validate customer has selected all necessary options
	
	var errorColor = "#d92349";
	var normalColor = "#8E8E8E";	
	var valueslabel = "label_values";
	var topErrorMessage = "topErrorMessage";
	
	// Set the label color to normal	
	$(valueslabel).style.color = normalColor;
	
	//short term solution for ie7 bug.
	//if($('valueslabel').options.length == 2)
    //    $('values_select').options.selectedIndex = 1;

	
	if ($('values_select').options[$('values_select').selectedIndex].value == 'select')
	{		
		$(valueslabel).style.color = errorColor;
		$(topErrorMessage).update('Please select all options.');
		
		return false;
	}
	
	if ($('values_select').options[$('values_select').selectedIndex].text.indexOf('out of stock') >= 0)
	{
		$(valueslabel).style.color = errorColor;
		$(topErrorMessage).update('Option selected is out of stock.');
		return false;
	}
	
	if( $('quantity').value > 0 ){
		/* Quantity is hardcoded to 1 so this will always be true */
	}else{
		$(qtyLabel).style.color = errorColor;
		$(topErrorMessage).update('Please enter a quantity');
		return false;
	}
	
	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/servlet/Cart', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML = '<strong>Your item cannot be added to cart.</strong>';
			} else {			
				//show mini shopping cart here
				//ajax to get content, params: product_id,option_params,qty
				//jsp page to get sku
				new Ajax.Request(context_path + '/shopping_cart/ajax/mini_cart.jsp',
						  {
						    method:'get',
						    parameters: get_form_values('checkout_form')+'&'+'randid='+Math.random(),
						    onSuccess: function(transport){
								
								$('shopping-cart').innerHTML = transport.responseText;
								
								//show shopping-cart
								if($('shopping-cart').style.display == 'none'){
									toggleMiniCart();
									
									//close mini cart after 5 seconds
									setTimeout("closeMiniCart()",5000);
								}
								
						    },
						    onFailure: function(){  }
						  });
				
				
				// Upon success we display a message as well as update the numItems count in the header 
				//$('checkout_message').style.display = '';
				 //$('checkout_message').innerHTML = '<strong>Item has been added to your cart!</strong> <a href="' + context_path + '/agent/login?toshipping=true">Checkout</a>';
				new Ajax.Request(context_path + '/templates/ajax/numItems.jsp',
				  {
				    method:'get',
				    parameters: {randid: Math.random()},
				    onSuccess: function(transport){
				      $('numItems').innerHTML = transport.responseText;
				    },
				    onFailure: function(){  }
				  });
			}
		},
		postBody: get_form_values('checkout_form')
	});
	
	
}




function initialize_info_tab(){
	var general_tab_href = $('general_tab').firstDescendant();
	general_tab_href.onclick = function(){
		$('general_tab').className = 'active';
		$('care_tab').className = '';
		$('style_tab').className = 'last';
		$('general_box').show();
		$('care_box').hide();		
		$('style_box').hide();
	};
	
	var care_tab_href = $('care_tab').firstDescendant();
	care_tab_href.onclick = function(){
		$('general_tab').className = '';
		$('care_tab').className = 'active';
		$('style_tab').className = 'last';
		$('general_box').hide();
		$('care_box').show();		
		$('style_box').hide();
	};
	
	var style_tab_href = $('style_tab').firstDescendant();
	style_tab_href.onclick = function(){
		$('general_tab').className = '';
		$('care_tab').className = '';
		$('style_tab').className = 'last active';
		$('general_box').hide();
		$('care_box').hide();		
		$('style_box').show();
	};
}

//this allows submitting multiple skus
function submit_checkout_form2(context_path, suffix){
	//for each of the product, validate the options
	var pidsStr = $('product_ids' + suffix).value;
	var pids = pidsStr.split(',');
	
	if(hasNoQty(pids)){
		return;
	}
	
	var isValid = true;
	for(i=0;i < pids.length;i++){
		if(validateProductOptions(pids[i]) == false){
			isValid = false;
		}
	}
	
	if(isValid == false){
		return;
	}
	
	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/servlet/Cart', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message' + suffix).style.display = '';
				$('checkout_message' + suffix).innerHTML = '<strong>Your item cannot be added to cart.</strong>';
			} else {			
				//show mini shopping cart here
				//ajax to get content, params: product_id,option_params,qty
				//jsp page to get sku
				new Ajax.Request(context_path + '/shopping_cart/ajax/mini_cart.jsp',
						  {
						    method:'get',
						    parameters: get_form_values('checkout_form' + suffix)+'&'+'randid='+Math.random(),
						    onSuccess: function(transport){
								
								$('shopping-cart' + suffix).innerHTML = transport.responseText;
								
								//show shopping-cart
								if($('shopping-cart' + suffix).style.display == 'none'){
									toggleMiniCart();
									
									//close mini cart after 5 seconds
									setTimeout("closeMiniCart()",5000);
								}
								
						    },
						    onFailure: function(){  }
						  });
				
				
				// Upon success we display a message as well as update the numItems count in the header 
				//$('checkout_message' + suffix).style.display = '';
				 //$('checkout_message').innerHTML = '<strong>Item has been added to your cart!</strong> <a href="' + context_path + '/agent/login?toshipping=true">Checkout</a>';
				new Ajax.Request(context_path + '/templates/ajax/numItems.jsp',
				  {
				    method:'get',
				    parameters: {randid: Math.random()},
				    onSuccess: function(transport){
				      $('numItems').innerHTML = transport.responseText;
				    },
				    onFailure: function(){  }
				  });
			}
		},
		postBody: get_form_values('checkout_form' + suffix)
	});
	
}

function validateProductOptions(pid){
	var subfix = '';
	if(pid > 0){
		subfix = '_'+pid;
	}

	// Validate customer has selected all necessary options

	var errorColor = "#d92349";
	var normalColor = "#8E8E8E";
	var colorLabel = "label_color"+subfix;
	var sizelabel = "label_size"+subfix;
	var topErrorMessage = "topErrorMessage"+subfix;
	
	if( $('quantity'+subfix).value > 0 ){
		
		// Set the label color to normal
		$(colorLabel).style.color = normalColor;
		$(sizelabel).style.color = normalColor;
		
		//short term solution for ie7 bug.
		if($('size_select'+subfix).options.length == 2)
	        $('size_select'+subfix).options.selectedIndex = 1;
	
		
		if ($('color_select'+subfix).options[$('color_select'+subfix).selectedIndex].value == 'select' ||
			$('size_select'+subfix).options[$('size_select'+subfix).selectedIndex].value == 'select')
		{
			$(colorLabel).style.color = errorColor;
			$(sizelabel).style.color = errorColor;
			$(topErrorMessage).update('Please select all options.');
			$(topErrorMessage).show();
			
			return false;
		}
		
		if ($('size_select'+subfix).options[$('size_select'+subfix).selectedIndex].text.indexOf('out of stock') >= 0)
		{
			$(sizelabel).style.color = errorColor;
			$(topErrorMessage).update('Option selected is out of stock.');
			return false;
		}
				
	}
	
	$(topErrorMessage).hide();
	
	return true;
}

function hasNoQty(pids){
	
	for(i=0;i < pids.length;i++){

		var subfix = '';
		if(pids[i] > 0){
			subfix = '_'+pids[i];
		}
		
		if( $('quantity'+subfix).value > 0 ){
			return false;
		}
	}
	
	return true;
}

function closeMiniCart(){
	if($('shopping-cart').style.display != 'none'){
		toggleMiniCart();
	}
}

function add_dressing_room(context_path){
	var errorColor = "#d92349";
	var normalColor = "#8E8E8E";
	var colorLabel = "label_color";
	var sizelabel = "label_size";
	var topErrorMessage = "topErrorMessage";
	
	// Set the label color to normal
	$(colorLabel).style.color = normalColor;
	$(sizelabel).style.color = normalColor;
	
	// Clear out the error messages
	$(topErrorMessage).update('');
	
	//short term solution for ie7 bug.
	if($('size_select').options.length == 2)
        $('size_select').options.selectedIndex = 1;

	
	if ($('color_select').options[$('color_select').selectedIndex].value == 'select' ||
		$('size_select').options[$('size_select').selectedIndex].value == 'select')
	{
		$(colorLabel).style.color = errorColor;
		$(sizelabel).style.color = errorColor;
		$(topErrorMessage).update('Please select all options.');
		
		return false;
	}

	// POST - async post because the user does NOT get taken to the shopping cart by design
	new Ajax.Request(context_path + '/list_item/add_item_do', {
		method: 'post',
		onSuccess: function(transport) {
			if (transport.getHeader("ACDC_ERROR") == 't') {
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML =  transport.responseText;
			} else {			
				$('checkout_message').style.display = '';
				$('checkout_message').innerHTML = 'Your item has been added to the wishlist. <a href="' + context_path + '/list_item/list" style="color: #FF66BC">View Wishlist</a>.';
			}
		},
		postBody: 'agent_sku_list_type_refcode=DRESSING_ROOM&' + get_form_values('checkout_form')
	});
}

var GA_oosTriggered = false;	// trigger only once per page
// this is caleld when dropdown initialize, and called when dropdown updates
function gaTrackingOOSEvent(){
	if (!GA_oosTriggered){
		if (jQuery('#out_of_stock_span').length && jQuery('#out_of_stock_span').css('display') != 'none'){
			// for single product pages, if 'out_of_stock_span' span is visible, trigger
			GA_oosTriggered = true;
			_gaq.push(['_trackEvent', 'Products', 'Out-of-Stock Product View', 'SKU']);
			//alert('oos');
		}
		jQuery('.in-stock').each(function(){
			// for multiple product pages (swim), if any of its in-stock class span shows "Out of stock", trigger
			if (jQuery(this).html() == 'Out of stock'){
				GA_oosTriggered = true;
				_gaq.push(['_trackEvent', 'Products', 'Out-of-Stock Product View', 'SKU']);
				//alert('oos');
			}
		});
	}
}

// this is called when user clicks on dropdown
function gaTrackingClickDropdownEvent(dropdown){
	onClick=_gaq.push(['_trackEvent','Products',dropdown,dropdown]);
	//alert('click: '+dropdown);
}


function show_all_reviews(number){        
     for (i = 0; i < number+1; i++){
            var extra = 'extra-review-'+i;           
            if(i>2){
            	document.getElementById(extra).style.display = "block";
            }
     }
}


///Fit Rating
function click_star_fit(num){
		num = parseInt(num);		
        cleanup_given_star('fit');
        for( i=1; i<num+1; i++) {
            var fit = 'fit'+i;
			document.getElementById(fit).style.backgroundPosition = "";
            document.getElementById(fit).style.backgroundImage = "url('/css/images/review-ico.png')";
            document.getElementById(fit).style.backgroundRepeat = 'no-repeat';
           	document.getElementById(fit).style.backgroundPosition = '0 bottom';
        }
        document.getElementById('starsGivenFit').value = num;
}
function cleanup_given_star(given_star){
                for(i=1; i<6; i++) {
                var name = given_star+i;

                document.getElementById(name).style.backgroundPosition = "0 0";
                document.getElementById(name).style.backgroundImage = '';
        }

}

//Style rating
function click_star_style(num){
		num = parseInt(num);		
        cleanup_given_star('style');

        for(i=1; i<num+1; i++) {
            var style = 'style'+i;
            document.getElementById(style).style.backgroundPosition = "";
            document.getElementById(style).style.backgroundImage = "url('/css/images/review-ico.png')";
            document.getElementById(style).style.backgroundRepeat = 'no-repeat';
            document.getElementById(style).style.backgroundPosition = '0 bottom';
        }

        document.getElementById('starsGivenStyle').value = num;
}



//Overall rating
function click_star_overall(num){
		num = parseInt(num);		
        cleanup_given_star('overall');

        for(i=1; i<num+1; i++) {
            var overall = 'overall'+i ;
            document.getElementById(overall).style.backgroundPosition = "";
            document.getElementById(overall).style.backgroundImage = "url('/css/images/review-ico.png')";
            document.getElementById(overall).style.backgroundRepeat = 'no-repeat';
            document.getElementById(overall).style.backgroundPosition = '0 bottom';
        }

        document.getElementById('starsGivenOverall').value = num;
}



function writereview(path, pid){
        var url = path;
        jQuery.ajax({
           type: "POST",
           url: url,
           data: 'product_id='+pid,
           dataType: "html",
           success: function(response){                
                $('write-a-review').innerHTML = response;
          }
         });
}


function submit_product_review(path){
        var url = path;
        jQuery.ajax({
           type: "POST",
           parameters : {
				randid : Math.random()
		   },
           url: url,
                   data: get_form_values('product_review_form'),
           dataType: "html",
           success: function(response){
                var json_string = response;
                if(json_string.length<100){                		
                		//document.getElementById('review-success-popup').style.display = 'block';                        
                        var url = json_string;                                              
                        window.location.href = url;                        
                }
                else {   
                	  setTimeout("initialRating()", 2000);             		
                      $('write-a-review').innerHTML = response;                      
                }
          }
         });
}

function showReviewAddSuccessfulPopup() {
     document.getElementById('review-success-popup').style.display = 'block';
}



function initialRating() {		
		if(document.getElementById('input_review_by').value.length>0) {
			document.getElementById('flname').checked = true;
		}
        var fit = document.getElementById('starsGivenFit').value;
        var style = document.getElementById('starsGivenStyle').value;
        var overall = document.getElementById('starsGivenOverall').value;
        if(fit>0) {
                click_star_fit(fit);
        }
        if(style>0) {
                click_star_style(style);
        }
        if(overall>0) {
                click_star_overall(overall);
        }
}

function textCounter(obj, wordLen) {
        var len = obj.value.split(/[\s]+/);
        if(len.length > wordLen){
                alert("Please enter fewer than " + wordLen + " words");
                obj.oldValue = obj.value!=obj.oldValue?obj.value:obj.oldValue;
                obj.value = obj.oldValue?obj.oldValue:"";
                return false;
        }
        return true;
}


function radioChecker( this_value ) {
 if(this_value.length > 0) {
    document.getElementById('flname').checked = true;
  }
}


function initialize_info_tab_review(){
	var general_tab_href = $('general_tab').firstDescendant();
	general_tab_href.onclick = function(){
		$('general_tab').className = 'active';
		$('care_tab').className = '';		
		$('style_tab').className = '';
		$('reviews_tab').className = 'last';
		$('general_box').show();
		$('care_box').hide();		
		$('style_box').hide();
		$('reviews_box').hide();
	};
	
	var care_tab_href = $('care_tab').firstDescendant();
	care_tab_href.onclick = function(){
		$('general_tab').className = '';
		$('care_tab').className = 'active';
		$('style_tab').className = '';
		$('reviews_tab').className = 'last';
		$('general_box').hide();
		$('care_box').show();		
		$('style_box').hide();
		$('reviews_box').hide();
	};
	
	var style_tab_href = $('style_tab').firstDescendant();
	style_tab_href.onclick = function(){
		$('general_tab').className = '';
		$('care_tab').className = '';
		$('style_tab').className = 'active';
		$('reviews_tab').className = 'last';
		$('general_box').hide();
		$('care_box').hide();		
		$('style_box').show();
		$('reviews_box').hide();
	};
	
	var reviews_tab_href = $('reviews_tab').firstDescendant();
	reviews_tab_href.onclick = function(){
		$('general_tab').className = '';
		$('care_tab').className = '';
		$('style_tab').className = '';
		$('reviews_tab').className = 'last active';
		$('general_box').hide();
		$('care_box').hide();		
		$('style_box').hide();
		$('reviews_box').show();
	};
}




