$().ready(function() {
	if($('#btnPartFinderBody').length){
		$('#btnPartFinderBody').click(partFinderSubmit);
	}
	if($('#btnPartFinderNav').length){
		$('#btnPartFinderNav').click(partFinderSubmit);
	}
	if($('#btnNavSearch').length){
		$('#btnNavSearch').click(searchFormSubmit);
	}
	if($('#btnNavSearchModel').length){
		$('#btnNavSearchModel').click(modelFinderSubmit);
	}
	if($('#btnMainSearchModel').length){
		$('#btnMainSearchModel').click(modelFinderSubmit);
	}
	if($('#btnOpSearchByModel').length){
		$('#btnOpSearchByModel').click(operatorManualSearchByModelNumber);
	}
	$('input').keypress(function(e) {
	    e = e || window.event;
	    if (e) {
	    	var charCode = e.charCode || e.keyCode || e.which;
       		if (charCode == 13) {
		        var inputElemId = $(this).attr('id');
		        if(inputElemId == 'main_search'){
		        	$('#btnNavSearch').click();
		        }else if(inputElemId == 'part_number_body'){
		        	$('#btnPartFinderBody').click();
		        }else if(inputElemId == 'model_number'){
		        	$('#btnMainSearchModel').click();
		        }else if(inputElemId == 'part_number_nav'){
		        	$('#btnPartFinderNav').click();
		        }else if(inputElemId == 'model_number_side'){
		        	$('#btnNavSearchModel').click();
		        }
		    }
	    }
	});
});
var operatorManualSearchByModelNumber = function(){
	clearErrMsgDiv();
	var inputElemValue = $.trim($('#model_number').val());
	var defaultText = $(this).attr('data-defaultText');//storing default text from prop file as value in custom attribute
	if($('#serial_number').length){
		var serialNumber = $('#serial_number').val();
		if(serialNumber.indexOf('Enter') > -1){
			serialNumber = '';
		}
	}else{
		var serialNumber = '';
	}
	if(validateInput(defaultText, inputElemValue)){
		modelFinderUrl = 'http://manuals.mtdproducts.com/mtd/Public.do?model_num='+inputElemValue+'&serial_num='+serialNumber+'&doSearch=Y';
		window.open(modelFinderUrl,'','toolbar=no,width=800,height=575,scrollbars=yes,location=no');
	}else{
		if($('#errMsgDisplay').length){
			$('#errMsgDisplay').html('Please enter required information.');
		}
	}
};
var modelFinderSubmit = function(){
	clearErrMsgDiv();
	var inputElemName = '#model_number';
	if($(this).attr('id') == 'btnNavSearchModel'){
		inputElemName = inputElemName + '_side';
	}
	var inputElemValue = $.trim($(inputElemName).val());
	var defaultText = $(this).attr('data-defaultText');//storing default text from prop file as value in custom attribute
	if(validateInput(defaultText, inputElemValue)){
		$('#arimn').val(inputElemValue);
		var storeId = document.ARIModelFinderForm.storeId.value;
		if(storeId == '10101'){
			$('#ARIModelFinderForm').submit();
		}else{
			ajaxModelFinder($('#arimn').val());
		}
		
		return false;
	}else{
		if($('#errMsgDisplay').length){
			$('#errMsgDisplay').html('Please enter required information.');
		}
	}
};
var partFinderSubmit = function(){

	var inputElemName = '#part_number';
	var submitElemId = $(this).attr('id');
	if(submitElemId == 'btnPartFinderBody'){
		inputElemName = inputElemName + '_body';
	}else if(submitElemId == 'btnPartFinderNav'){
		inputElemName = inputElemName + '_nav';
	}
	var inputElemValue = $.trim($(inputElemName).val());
	var defaultText = $(this).attr('data-defaultText');//storing default text from prop file as value in custom attribute
	if(validateInput(defaultText, inputElemValue)){
		ajaxPartFinder(inputElemValue);
	}
};
var searchFormSubmit = function(){
	var defaultText = $(this).attr('data-defaultText');//storing default text from prop file as value in custom attribute
	var inputText = $.trim($('#main_search').val());
	if(validateInput(defaultText, inputText)){
		submitSimpleSearchForm(inputText);
	}
};
function validateInput(defaultText, submittedText){
	if(defaultText == submittedText || submittedText == ''){
		return false;
	}else{
		return true;
	}
}
function submitSimpleSearchForm(searchTerm){
	$("#search_txt").val(searchTerm);
	$("#SimpleSearchForm").submit();
	return false;
}
function ajaxPartFinder(searchTerm){
	$('.waitbox').jqmShow(); 
	$('#btnPartFinderBody').unbind('click', partFinderSubmit);//unbind the onclick event to prevent multiple submits
	var partFinderUrl = $.protocolServerNameAndContextRoot + '/MTDPartFinder' + $.standardQueryStringParams;
	var urlParams = {};
	urlParams.partFinderTerm = searchTerm;
	jQuery.each($.requiredAjaxCmdParams, function(name, val) {
        urlParams[name] = val;
    });
	$.ajax({
	    url: partFinderUrl,
	    data: urlParams,
	    type: 'POST',
	    cache: false,
	    dataType: 'json',
	    timeout: 20000,
	    success: function(json){
	    	/** success just means we have received a reply from the server. still need to parse response for errors */
	    	/* to view the complete response, uncomment this section - ***requires json2.js include**
			var jsonText = JSON.stringify(json, function (key, value) {	return value; });
			alert('json resp: '+jsonText);
			*/
			if(typeof(json.errorMessage) !== 'undefined' || typeof(json.errMap) !== 'undefined'){
				if(typeof(json.errorMessage) !== 'undefined'){
					$('.waitbox').jqmHide();
					$('.errMsgDisplay').append('<ul class="error"><li>'+json.errorMessage+'</li></ul>');
					$('.ajaxErrorMsg').jqmShow();
				}
				else if(typeof(json.errMap) !== 'undefined'){
					$('.waitbox').jqmHide();
					var errMap = json.errMap;
					$('.errMsgDisplay').append('<ul class="error">');
					for (var key in errMap) {
					    $('.errMsgDisplay ul').append('<li>'+key+'</li>');
					}
					$('.ajaxErrorMsg').append('</ul>');
					$('.ajaxErrorMsg').jqmShow();
				}
			}
			if(typeof(json.productId)!== 'undefined'){
				var bReplaced = false;
				if(typeof(json.bReplaced) !== 'undefined' && json.bReplaced == 'true'){
					bReplaced = true;
				}
				loadProductQuickViewModal(json.productId,bReplaced,searchTerm);
			}
	    },
	    error: function(XMLHttpRequest, textStatus, errorThrown){
	    	//alert('XMLHttpRequest: '+ XMLHttpRequest.getResponseHeader("Content-Type") +'/ntextStatus: '+textStatus + '/nerrThrown: ' + errorThrown);
	    	$('.waitbox').jqmHide();
     		$('.errMsgDisplay').append('<ul class="error"><li>Unable to complete request. Please try again.</li></ul>');
     		$('.ajaxErrorMsg').jqmShow();
  		}
	});
	$('#btnPartFinderBody').bind('click', partFinderSubmit);//re-bind the onclick event 
}
function ajaxModelFinder(searchTerm){
	$('.waitbox').jqmShow();
	if($('#btnMainSearchModel').length){ 
		$('#btnMainSearchModel').unbind('click', modelFinderSubmit);//unbind the onclick event to prevent multiple submits
	}
	
	var partFinderUrl = $.protocolServerNameAndContextRoot + '/MTDModelFinderAjax' + $.standardQueryStringParams;
	var urlParams = {};
	urlParams.bAjaxSubmit = 'true';
	urlParams.modelName = searchTerm;
	jQuery.each($.requiredAjaxCmdParams, function(name, val) {
        urlParams[name] = val;
    });
	$.ajax({
	    url: partFinderUrl,
	    data: urlParams,
	    type: 'POST',
	    cache: false,
	    dataType: 'json',
	    timeout: 20000,
	    success: function(json){
	    	/** success just means we have received a reply from the server. still need to parse response for errors */
	    	/* to view the complete response, uncomment this section - ***requires json2.js include*
			var jsonText = JSON.stringify(json, function (key, value) {	return value; });
			alert('json resp: '+jsonText);**/
			if(typeof(json.errorMessage) !== 'undefined' || typeof(json.userErrorMsg) !== 'undefined'){
				if(typeof(json.errorMessage) !== 'undefined'){
					$('.waitbox').jqmHide();
					$('.errMsgDisplay').append('<ul class="error"><li>'+json.errorMessage+'</li></ul>');
					$('.ajaxErrorMsg').jqmShow();
				}else if(typeof(json.userErrorMsg) !== 'undefined'){
					$('.waitbox').jqmHide();
					$('.errMsgDisplay').append('<ul class="error">');
				    $('.errMsgDisplay ul').append('<li>'+json.userErrorMsg+'</li>');
					$('.ajaxErrorMsg').append('</ul>');
					$('.ajaxErrorMsg').jqmShow();
				}
			}
			$('.waitbox').jqmHide();
			if(typeof(json.categoryId)!== 'undefined'){
				categoryRedirectUrl = $.protocolServerNameAndContextRoot + '/CategoryDisplayView' + $.standardQueryStringParams 
				+ '&categoryId='+json.categoryId + '&isModelCategory='+json.isModelCategory + '&useSEOUrl='+json.useSEOUrl;
				window.location.href = categoryRedirectUrl;
			}
	    },
	    error: function(XMLHttpRequest, textStatus, errorThrown){
	    	//alert('XMLHttpRequest: '+ XMLHttpRequest.getResponseHeader("Content-Type") +'/ntextStatus: '+textStatus + '/nerrThrown: ' + errorThrown);
	    	$('.waitbox').jqmHide();
     		$('.errMsgDisplay').append('<ul class="error"><li>Unable to complete request. Please try again.</li></ul>');
     		$('.ajaxErrorMsg').jqmShow();
  		}
	});
	if($('#btnMainSearchModel').length){ 
		$('#btnMainSearchModel').bind('click', modelFinderSubmit);//re-bind the onclick event 
	}
}
function loadProductQuickViewModal(productId,bReplaced,origSearchTerm){
	$('.waitbox').jqmHide();
	var productQuickViewUrl = $.protocolServerNameAndContextRoot + '/ProductQuickView' + $.standardQueryStringParams + '&productId='+productId;
	if(typeof(bReplaced) !== 'undefined'){
		productQuickViewUrl += '&bReplaced=' + bReplaced;
		if(typeof(origSearchTerm) !== 'undefined'){
			productQuickViewUrl += '&replacedPart='+origSearchTerm;
		}
	}
	$('#jqModal').jqm({
		ajax:productQuickViewUrl,
		modal: true
	});
	$('#jqModal').jqmAddClose('.close');
	$('#jqModal').jqmShow(); 
	positionModal($('#jqModal'));
}
function clearErrMsgDiv(){
	if($('#errMsgDisplay').length){
		$('#errMsgDisplay').html('');
	}
}
