/*!
Minify this before production and put the minified version in
production/SophioPartsCatalog.min.js  !!!!
*/
// JavaScript Document
// tooltip function
jQuery(document).ready(function() {
	jQuery().ajaxStop(jQuery.unblockUI); 	
	jQuery('#sophioNavigation a,#minicart a').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: "+++", 
		opacity: 0.85 
	});

	jQuery('.ui-state-default').hover(
	   function(){jQuery(this).addClass('ui-state-hover');}, 
	   function(){jQuery(this).removeClass('ui-state-hover');
	   });
	
	//	if has paging then use ajax for that too
	if (typeof SophioAjaxCatalog!=="undefined" && typeof SophioAjaxCatalog.getParts!=="undefined"){
	jQuery('a.paginglink')
	.attr('href','#')
	.click(function(){
	SophioAjaxCatalog.getParts(jQuery(this).attr("rel"));
	return false;
	});							  	
	}
	
});


function filterRelParts(cCompId,cIllustration) {
				try {
					if (cCompId=="All") {
					jQuery('table[name="'+cIllustration+'"] tr[rel="related-parts-table-row"]').each(function(){jQuery(this).show();});
					} else  {
						jQuery('table[name="'+cIllustration+'"] tr[rel="related-parts-table-row"]').each(function(){						
						jQuery(this).css('display',(jQuery(this).attr('name')==cIllustration+'-'+cCompId)?'':'none');				
						});
					}
				} catch (err) {}
}

function getRelatedPartsCost(cCompId,cIllustration,cSku,cSectionId,cCatalog) {	
	jQuery.blockUI({timeout:60000,theme: true,
	title:    'Retreiving Price and Availability...',
	message:'<p align="center"><img src="sophio-shared-assets/js/jquery/ajax-loader-blue-bar.gif"/></p>',
	overlayCSS:  { backgroundColor:'#000',opacity: '0.4'}}); 	
		jQuery.getJSON("GetOERelatedPartsPrice.epc?cSku="+cSku+"&compid="+cCompId+"&catalog="+cCatalog,
			function(data){
			jQuery.unblockUI();
				if (!data.success) {
				jQuery.jGrowl('Part#: '+cSku+' cannot be ordered this time!',{ header: 'System Notification',sticky: true });
				alert('Part#: '+cSku+' cannot be ordered this time!');        			  			
				return false ;
				}
			jQuery('#txSup_'+cSectionId).val(data.data[0].sup);
			jQuery('#txSku_'+cSectionId).val(data.data[0].partno);
			jQuery('#txMFR_'+cSectionId).val(data.data[0].mfgname);
			jQuery('#txMinQty_'+cSectionId).val(data.data[0].minqty);
			jQuery('#txList_'+cSectionId).val(data.data[0].list);
			jQuery('#txPrice_'+cSectionId).val(data.data[0].user);
			jQuery('#txCore_'+cSectionId).val(data.data[0].core);
			jQuery('#txQtyAvail_'+cSectionId).val(data.data[0].qtyavail);
			jQuery('#txDesc_'+cSectionId).val(data.data[0].description);
			jQuery('#txImage_'+cSectionId).val(data.data[0].smartpage);
			jQuery('#txItempk_'+cSectionId).val(data.data[0].itempk);
			jQuery('#txWeight_'+cSectionId).val(data.data[0].txWeight);
			
			jQuery('#relPartsBuyPanel-'+cSectionId+' span.partlistprice').html(data.data[0].listI18N);
			jQuery('#relPartsBuyPanel-'+cSectionId+' span.partsellprice').html(data.data[0].userI18N);
			
			jQuery('#getPrice-'+cSectionId).hide();
			jQuery('#relPartsBuyPanel-'+cSectionId).slideDown(1000,function(){
				var top = jQuery('#relPartsBuyPanel-'+cSectionId).offset().top-100;
				jQuery('html,body').animate({scrollTop: top}, 100);
		});
		jQuery.jGrowl('Price and Availability Retrieved Successfully!',{ header: 'System Notification'});
	});
return false;
}



function checkmmbuy(){
      var returnStr=false;  
	  var catArr=document.getElementsByName('mmbuy'); 
      for (var i=0; i<catArr.length; i++)
	  {      
	  if (catArr[i].checked ){
       returnStr=true;
        break;
      }      
     }
	if (returnStr){
   return true;
	}else {
	  window.alert("Please select at least one item.");
      return false;
	  }
}


function updateMiniCart() {
	// display a message
	jQuery.jGrowl('Updating Shopping Cart Display...!',{ header: 'System Notification'});
	jQuery('#minicart').block({message: '<span id="ajaxIndicatorImage" style="margin-left:10px; position:relative; top:2px;"><img src="sophio-shared-assets/js/jquery/ajax-loader.gif"/></span>' , overlayCSS:  { backgroundColor:'#000', opacity: '0.1'}}); 
	jQuery.get("minicartajax.wws", function(data){
  		jQuery("#minicart").html(data);
		jQuery('#minicart').unblock();
		jQuery.jGrowl('Your Shopping Cart was Updated!',{ header: 'System Notification'});
		});
	 if (jQuery('#minicartmini').length>0) {
	  jQuery('#minicartmini').block({message: '<span id="ajaxIndicatorImage" style="margin-left:10px; position:relative; top:2px;"><img src="sophio-shared-assets/js/jquery/ajax-loader.gif"/></span>' , overlayCSS:  { backgroundColor:'#000', opacity: '0.1'}});
	 jQuery.get("minicartajax.wws?tpl=wogcartinfo.wws", function(data){
  		jQuery("#minicartmini").html(data);
		jQuery('#minicartmini').unblock();
		});
	 }
	
}

// submits the part form non ajax version
function SubmitSingleItemJ(cId){
	var singleForm=jQuery('form#epcaddsingleitem');
	jQuery('input.autoupdate', singleForm).each(function() {
		var t=this.name;
		this.value=jQuery('#'+t.replace('999999',cId)).val();
    });
	singleForm[0].submit();
} 


// submits the part form via ajax
function SubmitSingleItemJAjax(cId){
	var singleForm=jQuery('form#epcaddsingleitem');
	var responseTarget='#divlineitem_'+cId
	jQuery('input.autoupdate', singleForm).each(function() {
		var t=this.name;
		this.value=jQuery('#'+t.replace('999999',cId)).val();
    });
	jQuery('#epcaddsingleitem').ajaxSubmit({url:'additemajax.wws',dataType:'json',beforeSubmit: showUserMessage,									  
									  success:function(data,statusText,form) {
										  //console.log(data,statusText,form);
	try
  {
	 var defMessage=""
	  if (data.success) {
		  jQuery(responseTarget).html('<span class="ui-state-highlight">Item in Cart!</span>').effect("highlight",{},1500);	
		   jQuery.jGrowl('Item was succesfully added to your shopping cart!',{ header: 'System Notification'});	
		   if ( jQuery("#minicart").length > 0 ) {	updateMiniCart();}
		   defMessage="The part has been successfuly added to your shopping cart.";
	  }
	   else {
		  jQuery.jGrowl('Item was NOT added to your shopping cart!'+'\n'+data.msg,{ header: 'System Notification',sticky: true });
	  }
			 jQuery.unblockUI();
			 if (jQuery('#SophioAddToCartResponseDialog').length==0){	
					jQuery('<div id="SophioAddToCartResponseDialog" title="System Message">\
						   <div style="padding:0.7em; font-size:14px;" class="ui-state-highlight ui-corner-all">\
						   <span><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-info"/>\
						   <span id="SophioAddToCartResponseDialogMsg"></span></span></div></div>')
							.dialog({
								bgiframe: true,
								modal: true,
								width:600,
								autoOpen: false,
								draggable: false,
								resizable: true ,
								buttons: {
								  "Continue Shopping": function() {
										jQuery(this).dialog('close');
									},
									"Checkout" : function() {
										jQuery(this).dialog('close');
										// window.location=window.location.protocol+'//'+window.location.hostname+'/validateshoppingcart.wws';
										if (typeof SophioAjaxCatalog !== 'undefined' && typeof SophioAjaxCatalog.preventPageLeave !== 'undefined'){
										// enable page leave
										SophioAjaxCatalog.preventPageLeave=false;
										}

										window.location.href='validateshoppingcart.wws';

									},	
									"Shopping Cart": function() {
										jQuery(this).dialog('close');
										//window.location=window.location.protocol+'//'+window.location.hostname+'/shoppingcart.wws';
										if (typeof SophioAjaxCatalog !== 'undefined' && typeof SophioAjaxCatalog.preventPageLeave !== 'undefined'){
										// enable page leave
										SophioAjaxCatalog.preventPageLeave=false;
										}
										window.location.href='shoppingcart.wws';
									}																										
								}
							});
					}
					
					jQuery('#SophioAddToCartResponseDialogMsg').html((data.msg!=='')?data.msg:defMessage+'<br/>\
						   <b>Please select an action below!</b>')
					
					// show error dialog
					jQuery('#SophioAddToCartResponseDialog').dialog('open');
	 
  }
catch(err)
  {
   jQuery.jGrowl('Item was NOT added to your shopping cart!',{ header: 'System Notification',sticky: true });
    jQuery.unblockUI();
  }
										  }									  
									  }); 

									  return false;
	}

function showUserMessage(formData, jqForm, options) {
	jQuery.blockUI({timeout:60000,theme: true,
	title:    'Adding item to your cart...',
	message:'<p align="center"><img src="sophio-shared-assets/js/jquery/ajax-loader-blue-bar.gif"/></p>',
	overlayCSS:  { backgroundColor:'#000',opacity: '0.4'}}); 
}


if(typeof (tmpl) !== 'function') {
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript	  
	  str.replace(/[\r\t\n]/g, " ")
   .replace(/'(?=[^%]*%>)/g,"\t")
   .split("'").join("\\'")
   .split("\t").join("'")
   .replace(/<%=(.+?)%>/g, "',$1,'")
   .split("<%").join("');")
   .split("%>").join("p.push('")
   + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
}
/* 
updates a panel (targetID) from a url (cURL) 
needs blockUI componoment
*/
function jUpdatePanel(cURL,cTargetID,cBlockID) {
	cBlockID=cBlockID?cBlockID:cTargetID;
			jQuery('#'+cBlockID).block();
			jQuery.ajax({
  				url: cURL,
  				success: function(data) {
   					 jQuery('#'+cTargetID).html(data)
					 jQuery('#'+cBlockID).unblock();
					 },
				error:function(){jQuery('#'+cBlockID).unblock();}
				});	
}


function showSMPdetailPanel(oThis) {
	
	jQuery("#smp-part-details").dialog('open');
	
	jQuery("#smp-part-details-tabs-cid").attr("rel",jQuery(oThis).attr('rel'));
	if  (jQuery("#smp-part-details-tabs").tabs( "option", "selected" )!==0)
	{
		jQuery('#smp-part-details-tabs').tabs("option", "selected", 0);
		} else {
			getSMPImage(jQuery(oThis).attr('rel'));
		}
	
}

function setupSMPDetailPanel() {
	
	
	jQuery("#smp-part-details").show().dialog({
			autoOpen: false,
			height: 500,
			minHeight:300,
			width: 786,
			modal: true,
			title:'Parts Detail',
			buttons: {				
				Close: function() {
					jQuery(this).dialog('close');
				}
			}
		});
	
	jQuery("#smp-part-details-tabs").show().tabs();
	
	
	jQuery('#smp-part-details-tabs').bind('tabsselect', function(event, ui) {
	var cID=jQuery("#smp-part-details-tabs-cid").attr("rel");														 
	if (ui.index==0)
	{
		getSMPImage(cID);
		}
	if (ui.index==1) {
		getSMPBuyerBrowse(cID);
	}
	
	if (ui.index==2) {
		getSMPDocuments(cID);
	}
	if (ui.index==3) {
		getSMPAttributes(cID);
	}
	/*
     ui.options // options used to intialize this widget
     ui.tab // anchor element of the selected (clicked) tab
     ui.panel // element, that contains the contents of the selected (clicked) tab
     ui.index // zero-based index of the selected (clicked) tab
	 */
    });
		}

function getSMPImage(cID)
{
	if (jQuery('#smp-part-details-tabs-1').attr('rel')!==cID)
		{
		// clear current image	
		jQuery('#smp-part-details-tabs-1-image').html("");	
		// bloc section
		jQuery("#smp-part-details-tabs").block();
		jQuery.ajax({ 
		url:		"getSMPDetail.epc?type=image&ajax=true&fullJSON=true&Id="+cID,
		dataType:	"json",
		success : 	function(data)
				{ 	
					jQuery(data.data).each(function(){
						jQuery("<img/>")
						.attr("src",this.id)
						.attr("width",Math.min(640,this.width))
						.appendTo(jQuery('#smp-part-details-tabs-1-image'));
					});
					//jQuery('#smp-part-details-tabs-1-image')
					//.attr("src",data.data[0].name)
					//.attr("width","400")					
					jQuery('#smp-part-details-tabs-1').attr('rel',cID);
					jQuery("#smp-part-details-tabs").unblock();					
				},

		error:		function(resp)
				{
					alert("AJAX communication error occured.");
					jQuery("#smp-part-details-tabs").unblock();	
				}
		});
		}
}


function getSMPBuyerBrowse(cID)
{
	if (jQuery('#smp-part-details-tabs-2').attr('rel')!==cID)
		{
		// clear current image	
		jQuery('#smp-part-details-tabs-2 tr:gt(0)').remove();	
		// bloc section
		jQuery("#smp-part-details-tabs").block();
		jQuery.ajax({ 
		url:		"getSMPDetail.epc?type=guide&ajax=true&fullJSON=true&Id="+cID,
		dataType:	"json",
		success : 	function(data)
				{ 	
					var cHtml="";
					if (data.data.length==0) {
						 cHtml='<tr><td colspan="5">No buyers guide available for this part!</td>'
					}
					jQuery(data.data).each(function(){
					 cHtml+='<tr>'+
							'<td align="left" class="ui-widget-content" width="130">'+this.make+'</td>'+
							'<td align="left" class="ui-widget-content" width="180">'+this.model+'</td>'+
							'<td align="left" class="ui-widget-content" width="70">'+this.year+'</td>'+
							'<td align="left" class="ui-widget-content" width="130">'+this.engine+'</td>'+
							'<td align="left" class="ui-widget-content" width="150">'+this.parttype+'</td>'+
						'</tr>'	
					});
					jQuery('#smp-part-details-tabs-2 tr:eq(0)').after(cHtml);				
					jQuery('#smp-part-details-tabs-2').attr('rel',cID);
					jQuery("#smp-part-details-tabs").unblock();					
				},

		error:		function(resp)
				{
					alert("AJAX communication error occured.");
					jQuery("#smp-part-details-tabs").unblock();	
				}
		});
		}
}


function getSMPDocuments(cID)
{
	if (jQuery('#smp-part-details-tabs-3').attr('rel')!==cID)
		{
		// clear current image	
		jQuery('#smp-part-details-tabs-3 tr:gt(0)').remove();	
		// bloc section
		jQuery("#smp-part-details-tabs").block();
		jQuery.ajax({ 
		url:		"getSMPDetail.epc?type=docs&ajax=true&fullJSON=true&Id="+cID,
		dataType:	"json",
		success : 	function(data)
				{ 	
					var cHtml="";
					if (data.data.length==0) {
						 cHtml='<tr><td colspan="2">No documents available for this part!</td>'
					}
					jQuery(data.data).each(function(){
					 cHtml+='<tr>'+
							'<td align="left" class="ui-widget-content" width="130"><a target="_blank" href="'+this.filename+'"/>'+this.filename+'</a></td>'+
							'<td align="left" class="ui-widget-content" width="180">'+this.filedescription+'</td>'+
						'</tr>'	
					});
					jQuery('#smp-part-details-tabs-3 tr:eq(0)').after(cHtml);				
					jQuery('#smp-part-details-tabs-3').attr('rel',cID);
					jQuery("#smp-part-details-tabs").unblock();					
				},

		error:		function(resp)
				{
					alert("AJAX communication error occured.");
					jQuery("#smp-part-details-tabs").unblock();	
				}
		});
		}
}

function getSMPAttributes(cID)
{
	if (jQuery('#smp-part-details-tabs-4').attr('rel')!==cID)
		{
		// clear current image	
		jQuery('#smp-part-details-tabs-4 tr:gt(0)').remove();	
		// bloc section
		jQuery("#smp-part-details-tabs").block();
		jQuery.ajax({ 
		url:		"getSMPDetail.epc?type=attribs&ajax=true&fullJSON=true&Id="+cID,
		dataType:	"json",
		success : 	function(data)
				{ 	
					var cHtml="";
					if (data.data.length==0) {
						 cHtml='<tr><td colspan="2">No attributes available for this part!</td>'
					}
					jQuery(data.data).each(function(){
					 cHtml+='<tr>'+
							'<td align="left" class="ui-widget-content" width="130">'+this.attr+'</td>'+
							'<td align="left" class="ui-widget-content" width="180">'+this.val+'</td>'+
						'</tr>'	
					});
					jQuery('#smp-part-details-tabs-4 tr:eq(0)').after(cHtml);				
					jQuery('#smp-part-details-tabs-4').attr('rel',cID);
					jQuery("#smp-part-details-tabs").unblock();					
				},

		error:		function(resp)
				{
					alert("AJAX communication error occured.");
					jQuery("#smp-part-details-tabs").unblock();	
				}
		});
		}
}
