/**
 * This ensures that there is no conflict between JQuery and Prototype.
 * Note, to use JQuery in this JavaScript file, you should use the following 
 * convention:
 * $j(selector).function()
 * For Prototype, you may continue to use "$(selector).function".
 */
var $j = jQuery.noConflict();

/**
 * Execute an AJAX GET to the supplied URL. Note, for the onSuccess portion of
 * the AJAX GET, we will try to execute the onSuccess function (if one was supplied). 
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> url - The URL used for the AJAX Get
 *            <li> onSuccessFunctionName -The name of the javascript function to
 *            execute if the AJAX GET was successful. Note, this is not
 *            required.
 *            </ul>
 */
function executeAjaxGet(hashParam) 
{
	var url = hashParam.get('url');
	
	// Sanity check
	if (url == null || url.length == 0)
	{
		return;
	}
	
	new Ajax.Request(url, {
		method : 'get',
		onSuccess: function(transport) 
		{
			var onSuccessFunctionName = hashParam.get('onSuccessFunctionName');
			if(onSuccessFunctionName != null)
			{
				var evalString = onSuccessFunctionName + "(transport, hashParam)";
				eval(evalString);
			}
		},
		onFailure : function() {
			alert("There was an error executing the AJAX call.");
		}
	});
}

/**
 * Execute an AJAX POST to the supplied URL. Note, for the onSuccess portion of
 * the AJAX call, we will try to execute the onSuccess function (if one was supplied). 
 * 
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> url - The URL used for the AJAX Post. Note, this is required
 *            <li> onSuccessFunctionName -The name of the javascript function to
 *            execute if the AJAX POST was successful. Note, this is not
 *            required.
 *            <li> postBodyFunc - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 * 
 * @return
 */
function executeAjaxPost(hashParam)
{
	var url = hashParam.get('url');
	var postBodyFunc = hashParam.get('postBodyFunc');
	// Sanity check
	if (url == null || url.length == 0 || 
			postBodyFunc == null || postBodyFunc.length == 0)
	{
		return;
	}
	
	new Ajax.Request(url, {
		method: 'post',
		parameters: {randid: Math.random()},
		onSuccess: function(transport) 
		{
			var onSuccessFunctionName = hashParam.get('onSuccessFunctionName');
			if(onSuccessFunctionName != null)
			{
				var evalString = onSuccessFunctionName + "(transport, hashParam)";
				eval(evalString);
			}
		},
		onFailure : function() {
			alert("There was an error executing the AJAX call.");
		},
		postBody: eval(postBodyFunc)

	});
}


/**
 * Close the pop-up with the given element id.
 * 
 * @param elementId The id of the pop-up (div) element.
 * @return
 */
function closePopup(elementId) 
{
	// Sanity check
	if (elementId == null || elementId.length ==0)
	{
		return;
	}
	
	$(elementId).innerHTML = '';
	$(elementId).style.visibility = 'hidden';
}


function populateMiniCart(context_path){
	
	new Ajax.Request(context_path + '/shopping_cart/ajax/mini_cart.jsp',
			{
		method:'get',
		parameters: 'randid='+Math.random(),
		onSuccess: function(transport){
		//$('mini_cart').style.display = '';
		$('shopping-cart').innerHTML = transport.responseText;
		
		//if content is populated, we can show now
		toggleMiniCart();
	},
	onFailure: function(){  }
			});
}

jQuery(function(){

	new Ajax.Request(contextPath+'/templates/ajax/numItems.jsp', {
		method: 'get',
		parameters: {randid: Math.random()},
		onSuccess: function(transport) {
			$('numItems').innerHTML = transport.responseText;
		}
	});

});

/**
 * This is called as a result of the AJAX GET, which was initialized when the
 * user click on a link.
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> url - The URL used for the AJAX Post
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 * @return
 */
function getGenericPopup(transport, hashParam)
{
	var elementId = hashParam.get('elementId');
	if(elementId != null  && elementId.length > 0)
	{
		// Update the content
		$(elementId).update(transport.responseText);
		$(elementId).style.visibility = 'visible';
		$j('#' + elementId).fadeIn(100);
	}
}

/**
 * This function is called as a result of the AJAX POST, which was initialized
 * when the user the submit button or link.
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> url - The URL used for the AJAX Post
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            <li> hideId - The Id of the element that will be hidden once the
 *            AJAX call completes
 *            <li> showId - The Id of the element that will be displayed once
 *            the AJAX call completes, i.e. a "Thank you" message.
 *            </ul>
 */
function submitGenericPopup(transport, hashParam)
{
	var elementId = hashParam.get('elementId');	
	var hideElementId = hashParam.get('hideId');
	var showElementId = hashParam.get('showId');	
	
	//If no element Id was provided, we cannot continue. 
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}
	
	// Update the content.
	$(elementId).update(transport.responseText);

	// If there was an error, then display the error in the popup.
	if (transport.getHeader("ACDC_ERROR") == 't') 
	{	
		return;
	}

	if (hideElementId != null && showElementId != null)
	{
		$(showElementId).style.display= "block";
		$(hideElementId).style.display= "none";
	}
	
	setTimeout("$j('#" + elementId + "').fadeOut(2000)", 5000);
}



/**
 * This function is called as a result of the AJAX POST, which was initialized
 * when the user clicked to "Sign Up" link on "mailing_list.jsp".
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> url - The URL used for the AJAX Post
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 */
function submitMailingList(transport, hashParam)
{
	var elementId = hashParam.get('elementId');	
	
	//If no element Id was provided, we cannot continue. 
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}
	
	// Update the content.
	$(elementId).update(transport.responseText);
	
	// If we were able to successfully save user email address, 
	// then fade out the "thank you" page after five seconds.
	if (transport.responseText.search('thankYou') > 0)
	{
		setTimeout("$j('#" + elementId + "').fadeOut(2000)", 5000);
	}
}

/**
 * This is called as a result of the AJAX GET, which was initialized when the
 * user click on either the "Add a Address", "Edit" or "Delete" link on the
 * "shipping_address/view_all_body.jsp".
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 * @return
 */
function getShippingAddressPopup(transport, hashParam)
{
	var elementId = hashParam.get('elementId');

	// If no element Id was provided, we cannot continue. 
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}

	// Update the content
	$(elementId).update(transport.responseText);
	$(elementId).style.visibility = 'visible';
	fixSelectBoxAfterAjax();
}

/**
 * This is called as a result of the AJAX POST, which was initialized when the
 * user click on either the "Add Address", "Edit Address" or "Delete Address"
 * links.
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 * @return
 */
function submitShippingAddress(transport, hashParam)
{
	var elementId = hashParam.get('elementId');
	
	if (transport.getHeader("ACDC_ERROR") == 't') 
	{
		if(elementId != null  && elementId.length > 0)
		{
			$(elementId).update(transport.responseText);
		}
		fixSelectBoxAfterAjax();
		return;
	} 
	location.reload(true);
}
	

/**
 * This is called as a result of the AJAX GET, which was initialized when the
 * user click on either the "Add A Credit Card", "Edit" or "Delete" link on the
 * "credit_card/view_all_body.jsp".
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            </ul>
 * @return
 */
function getCreditCardPopup(transport, hashParam)
{
	var elementId = hashParam.get('elementId');
	
	// If no element Id was provided, we cannot continue. 
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}	
	// Update the content
	$(elementId).update(transport.responseText);
	$(elementId).style.visibility = 'visible';
	
	fixSelectBoxAfterAjax();
}


/**
 * This is called as a result of the AJAX POST, which was initialized when the
 * user click on either the "Add Credit Card", "Edit Credit Card" or "Delete
 * Credit Card" links.
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            <li> removeQueryString - A boolean that indicates whether to
 *            remove the query string from the URL or not.
 *            </ul>
 * @return
 */
function submitCreditCard(transport, hashParam)
{
	var elementId = hashParam.get('elementId');
	if (transport.getHeader("ACDC_ERROR") == 't') 
	{
		if(elementId != null  && elementId.length > 0)
		{
			$(elementId).update(transport.responseText);
		}
		fixSelectBoxAfterAjax();
		return;
	} 

	location.reload(true);
}



/**
 * This is called as a result of the AJAX GET, which was initialized when the
 * user click on either the "Find A Store" links.
 * 
 * @param transport
 *            The transport object from AJAX.
 * @param hashParam
 *            A Prototype Hash of the parameters, which includes but not limited
 *            to the following:
 *            <ul>
 *            <li> elementId - The function or code to execute after AJAX
 *            completes.
 *            <li> removeQueryString - A boolean that indicates whether to
 *            remove the query string from the URL or not.
 *            </ul>
 * @return
 */
function storeLocator(transport, hashParam)
{
	elementId = '#' + hashParam.get('elementId');
	
	//console.log(elementId);
	
	// Sanity check
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}

	// Update the content
	$j(elementId).empty();
	$j(elementId).append(transport.responseText);
	fixSelectBoxAfterAjax();
}


/*
 * ORIGINAL CALL FOR STORE LOCATOR
function storeLocator(transport, hashParam)
{
	var elementId = hashParam.get('elementId');
	
	// Sanity check
	if(elementId == null  || elementId.length == 0)
	{
		return;
	}

	// Update the content
	$(elementId).update(transport.responseText);
	fixSelectBoxAfterAjax();
}
*/


/**
 * Find a Store based on the zip-code or the state and city.
 */
function findStores(context_path)
{
	var url = context_path + '/store/locator_results.jsp';
	var postBodyFunc = "get_form_values(\'find_stores\')"
	executeAjaxPost(new Hash({url:url, elementId:'location-results-pagination', onSuccessFunctionName:'storeLocator', postBodyFunc:postBodyFunc}));
}


/**
 * Apply the Jquery style associated with the "Select" element after the AJAX
 * call completes.
 * 
 * @param elementIds
 *            A list of a comma separated element Ids.
 * @return
 */
function fixSelectBoxAfterAjax()
{
	$j(document).ready(function(){  
		$j('select').selectbox();
	});
}

/**
 * Update the given element with the number of remaining characters.
 * 
 * @param element
 *            The element (usually a textarea).
 * @param totalCharCount
 *            The total number of characters allowed
 * @param showId
 *            The id of the element that displays the number of characters
 *            remaining.
 * @param message
 *            The message with the text "REPLACE_ME" where the number of
 *            characters remaining should be placed.
 * @return
 */
function updateRemainingCharCount(element, totalCharCount, showId, message)
{
	var replace_me = "REPLACE_ME"
	var currentCharCount = element.value.length;
	var remaingCharCount = totalCharCount - currentCharCount;
	
	// Check if remaingCharCount is negative. If so, 
	// it indicates that the user entered too much characters. 
	if(remaingCharCount < 0)
	{
		var value = element.value.substring(0, totalCharCount);
		element.value = value;
		remaingCharCount = 0;
	}
	
	var updateText = message.replace(replace_me, remaingCharCount);
	$(showId).update(updateText);	
}

$j(document).ready(function(){
	$j('.scrollable').jScrollPane({
		scrollbarWidth : 3
	});
});

/**
 * Create a popup when user clicks on a link such as "Inquire About this Look" link, 
 * which may be found on the following pages:
 * <ul>
 * <li>/views/cat/collection_spring_2010_runway.jsp
 * <li>/views/cat/collection_srping_2010_lookbook.jsp
 * </ul>
 * @param parent The element that will contain this pop-up. 
 * @param title The title of tjhe popup
 * @param content The content to place in the pop-up.
 * @return
 */
function createGenericPopup(parent, title, content, style)
{
	if (content == null)
	{
		content =  "<p style='line-height:20px; text-transform: none;'>"
			+ "Although not every item in this look is available for purchase at"
			+ " <a href='http://www.millyny.com'>millyny.com</a> we can tell you the product details and" 
			+ " potentially help you find it one of Milly retailers around the globe."  
			+ " Contact our product specialist Kerry M. at"
			+ " <a href='mailto:stylist@millyny.com'>stylist@millyny.com </a>"
			+ " and she will get back to you in 24 hours.</p>"
	}
	
	var baseContent = "<div class='popup' id='genericPopup' style='" + style + "'>"
		+ "<div class='top'>&nbsp;</div><div class='bg'><div class='cnt'>"
		+ "<a href='#' class='close'>Close</a><h2>" + title + "</h2>"
		+  content + "</div><div><div class='bot'>&nbsp;</div></div>";

	if (document.getElementById("genericPopup") == null)
	{
		$(parent).insert(baseContent);
	}
	else
	{
		$('genericPopup').show();
	}
}

function openGenericSrcollablePopup(topPos, leftPos)
{
	$('scrollable-popup').show();
	$j(document).ready(function(){
		$j('#scrollable-popup').css({'top': topPos, 'left' : leftPos});
		$j('.scroller').jScrollPane({
			scrollbarWidth : 3
		});
	});
}

/**
 * This function is used on the return_no_account_body.jsp page.
 * 
 * @param hasAccount a boolean that indicates if the user has an account.
 * @return
 */
function switchView(hasAccount)
{	
	if (hasAccount == 'Yes')
	{
		$j('#accountEnabled').show(); 
		$j('#noAccount').hide();
		return;
	}
	$j('#accountEnabled').hide(); 
	$j('#noAccount').show();
}


/*
* This function is used on credit_card, shipping to hide and show state field based on selected country.

*/
function handleBillingCountrySelect(){
    if ($('country').options[$('country').selectedIndex].value == '1' || $('country').options[$('country').selectedIndex].value == '0'){
       //element = document.getElementById('state_id').style;
       //element.display='block'; 
       document.getElementById('shipping_state').style.display='block';
       document.getElementById('shipping_zip_code').style.display='block';
       //alert(11);
    }else{                       
       //element = document.getElementById('state_id').style;
       //element.display='none';
       document.getElementById('shipping_state').style.display='none';
       document.getElementById('shipping_zip_code').style.display='none';
       document.getElementById('shipping_state').value = '0';
       document.getElementById('shipping_zip_code').value='';
       //alert(22);
    }
}



function show_modal(path){
	var url = path;
	jQuery.ajax({
	   type: "GET",
	   url: url,
	   success: function(response){showModalDialog(response);}
	 });	
}




