/*
 * Product List page scripts for dynamically populating the product list using DWR
 * @author luisat
 */

// globals vars
// these global variables retain global event change data 
// such as the selected family or product from the drop 
// down filters
var familyListValue;
var productCategoryListValue;
var partnerListValue;
var defaultResultsValue = 10; 	
var currentPage = 1;
var familyRegex = /^(.+)-.+-.+$/;    // extract version from product family string
var versionRegex = /^.+-(.+)-.+$/;   // extract version from product family string
var osRegex = /^.+-.+-(.+-.+)$/;     // extract os from product family string	
var productCategoryRegex = /^.*thin.*client.*$/i;  // match the product category  
	
var cellBeanFuncs = [

	// first cell : type
	function(productBean) {
		var result ="<div style='width: 10px;'>";
		return result + "</div>"; 
	},
	// second cell: name and description
	function(productBean) {
		
		var result =  "<div class='listitem' style=\"width: 470px;\"><h3><a href='reflink'>" + productBean.productName + " </a></h3> " 
		+ "<p>" + productBean.description + "</p>";  			
		result = result.replace(/reflink/g, serverURL + "/partners/" + productBean.partnerKey + "/products/" + productBean.productKey);
		return result + "</div>";  				
	},
	
	// third cell: product image
	function(productBean) {   		
	
		var result =  "<div class='listitem'><a href='reflink'><img alt='alttext' src='imgsrc' width='100' height='85' style=\"margin: 0px 10px 0px 10px;\" /></a></div>";
		result = result.replace(/alttext/g, "Product Logo");
		result = result.replace(/reflink/g, serverURL + "/partners/" + productBean.partnerKey + "/products/" + productBean.productKey);
		result = result.replace(/imgsrc/g, serverURL + productBean.logo);  			
		return result;
	},
	
	// fourth cell: company logo
	function(productBean) {   		
	
		var result =  "<div class='listitem'><a href='reflink'><img alt='alttext' src='imgsrc' width='100' height='85' /></a></div>";
		result = result.replace(/alttext/g, "Company Logo");
		result = result.replace(/reflink/g, serverURL + "/partners/" + productBean.partnerKey);
		result = result.replace(/imgsrc/g, serverURL +  productBean.companyLogo);  			
		return result;
	}
];	
	
jQuery(document).ready( function() {
		
	var message1 = "<div align='center'><img src='" + serverURL + "/res/i/products_loading.gif' alt='Loading'></div>";	
	
	// show loading message
	jQuery("#productListContentTableMessage").append(message1);
	
	// initialize values
	captureValues();
	displayAdvancedOptions();		
	populate(0, 10);	   			
	   			
	//  DROP DOWN MENU EVENTS   			
	jQuery(".isDropDown").each(function() {                    	
		jQuery(this).change(function() {        		
			  
			// display loading message        		
			jQuery("#productListContentTableMessage").empty();
			jQuery("#productListContentTableMessage").append(message1);			
				    		        		
	    	// fetch and write new entries	        		
		    currentPage = 1;
    		captureValues();    					
			
			// if it's OS selection, it will override familyListValue with family-version-os		     
			if (jQuery(this).attr("id") !== "advOptionOS") {
				displayAdvancedOptions();
			}
			else {    						
				if(!StringUtils.isEmpty(jQuery(this).attr("value"))) {									
					familyListValue = jQuery(this).attr("value");
				}								
			}			
    		populate(0,10);     
    		
    		// RDY-1185     FINISH LINK!
    		jQuery("#siblingProductCategory").empty();
 			jQuery("#productCategoryLinkAndLogo").empty();   		  		    	
    		if(productCategoryRegex.exec(productCategoryListValue)) {    			
    			jQuery("#productCategoryLinkAndLogo").empty().append("<a href='http://www.citrix.com/English/partners/programs/fourthLevel.asp?programID=1681660&tlID=163199&flID=1859519' target='_blank'>Learn more about HDX Ready</a>");	
    		}
	    											
			DWRProductListController.getProductCategorySiblingFor(productCategoryListValue, {
				callback: function(sibling) {
					if(!StringUtils.isEmpty(sibling)) {
						jQuery("#siblingProductCategory").empty().append("<div class='hdxLinkLeft'><a href='" + serverURL + "/list/products?productCategory="+ sibling + "'>" + "View " +  sibling + "</a></div><div class='hdxLogo'><img src='" + serverURL + "/res/i/hdx_logo.jpg' title='HDX' border='0' width='34' height='20'></div>");
					}						
				},
				errorHandler: function() {
					// do nothing					
				},
				timeout:10000		
			});    		 		 		   
    	});
	});
	
	
	
	
	// ADVNACED OPTIONS: VERSION MENU EVENT
	jQuery("#advOptionVersion").change(function() {
		if(StringUtils.isEmpty(jQuery(this).attr("value"))) {
			jQuery("#advOptionOS").hide().empty();
			return;
		}
		
		familyListValue = jQuery(this).attr("value");
		
		var family = familyRegex.exec(familyListValue)[1];
		var version = versionRegex.exec(familyListValue)[1];
		
		if(StringUtils.isEmpty(family) || StringUtils.isEmpty(version)) {
			return;
		}
		
		DWRProductListController.getProductOS(family, version, { 
			callback: function(oses) {
				
				if(!oses || !ArrayUtils.isArray(oses) || oses.length == 0) {
					return;
				}
				
				var options = "<option value=''>All Operating Systems</option>";					  
				for(var i = 0; i < oses.length; i++) {
																		
					var titleStr = osRegex.exec(oses[i])[1];
					
					if(!StringUtils.isEmpty(titleStr)) {
						options = options.concat("<option value='" + oses[i]+ "'>" + titleStr + "</option>");
					}					
				}
				if(!StringUtils.isEmpty(options)) {
					jQuery("#advOptionOS").show();				
					jQuery("#advOptionOS").empty().append(options);															
				}				
			},
			errorHandler:function(message) { 			
				jQuery("#advOptionOS").hide().empty();
			 },
			timeout:5000
		});	
		currentPage = 1;
		populate(0,10);   	
	});		
});

function displayAdvancedOptions() {
	
	jQuery("#advOptionOS").hide();
			
	if(!StringUtils.isEmpty(familyListValue)) {	
					
		var family = familyRegex.exec(familyListValue)[1];
									
		DWRProductListController.getProductVersions(family, {
			callback: function(versions) {
				
				if(versions && ArrayUtils.isArray(versions) && versions.length > 0) {
							
					var options = "<option value=''>All Versions</option>";
					  
					for(var i = 0; i < versions.length; i++) {
													
						var titleStr = versionRegex.exec(versions[i])[1];
						
						if(!StringUtils.isEmpty(titleStr)) {
							options = options.concat("<option value='" + versions[i]+ "'>" + titleStr + "</option>");
						}					
					}
					if(!StringUtils.isEmpty(options)) {				
						jQuery("#advOptionVersion").empty().append(options);
						jQuery("#productFamilyAdvancedOptionsTitle").empty().append(family + " > ");
						jQuery("#linkAdvancedOptions").css("visibility","visible");
						//jQuery("#productFamilyAdvancedOptions").css("visibility","visible");									
					}				
				}
				else {
					jQuery("#linkAdvancedOptions").css("visibility","hidden");
					jQuery("#productFamilyAdvancedOptions").css("visibility","hidden");
				}
			},
			errorHandler: function() {
				jQuery("#productFamilyAdvancedOptions").css("visibility","hidden");
				jQuery("#linkAdvancedOptions").css("visibility","hidden");
			},
			timeout:5000		
		});
	}
	else {
		jQuery("#productFamilyAdvancedOptions").css("visibility","hidden");
		jQuery("#linkAdvancedOptions").css("visibility","hidden");
	}
	jQuery("#linkAdvancedOptions").click(function(){
	
		jQuery("#productFamilyAdvancedOptions").css("visibility","visible");
		return false;
		
	});
}



function populate(from,to) {
	
	var bean = {
		family:          StringUtils.trim(familyListValue),
		partner:         StringUtils.trim(partnerListValue),
		productCategory: StringUtils.trim(productCategoryListValue),
		to: to,
		from: from
	};
	
	DWRProductListController.getListContent(bean, { 
		callback: updateContentHandler,
		errorHandler:function(message) { 			
			jQuery("#productListContentTableMessage").append("<div align='center'>There are no products matching your criteria</div>");
		 },
		timeout:20000
	});	
}
	
function captureValues() {
	
	// extract all values from top level drop down menus
	jQuery(".isDropDown").each(function() {
	
		// capture familyDropDown value
		if (jQuery(this).attr("id") === "familyDropDown") {
			familyListValue = jQuery(this).attr("value");			
		}
		
		// capture productCategoryDropDown value
		if (jQuery(this).attr("id") === "productCategoryDropDown") {
			productCategoryListValue = jQuery(this).attr("value");
		} 
		
		// capture partnerDropDown value
		if (jQuery(this).attr("id") === "partnerDropDown") {
			partnerListValue = jQuery(this).attr("value");
		}  		  
	});  	
}

function navigateTo(pageNumber) {
	currentPage = pageNumber;
	var fromNum = pageNumber * defaultResultsValue - defaultResultsValue;					
	var toNum = pageNumber * defaultResultsValue;					
	populate(fromNum, toNum);				
}

// populate content
function updateContentHandler(pageResult) {
	
	  
	ws.cr.util.removeAllRows("productListContentTable");		
		
	// hide all tables
	jQuery("#productListContentTable").hide();	
	jQuery("#productListContentTableHeader").hide();		
	jQuery("#productListContentTableMessage").empty();
	jQuery("#pagination").empty();

	var message2 = "<div align='center'>There are no products matching your criteria</div>";
	
	if (pageResult && pageResult.results) {  				
		if (pageResult.results.length === 0) { 									
			jQuery("#productListContentTableMessage").append(message2);
		}
		else {																	
			// populate core product table
			jQuery("#productListContentTable").show();
			jQuery("#productListContentTableHeader").show();
			ws.cr.util.addRows("productListContentTable", pageResult.results, cellBeanFuncs, { 			
				rowOptions: function(num, item) {
					
					// leadership
					if(item.level === 0) {									    	
						return "class='listItemLeadership'";
					}
					// core
					else {
						return "class='listItemCore'";
					}			    	
			  	},			
			  	  	
			  	cellOptions: function(num, item) {
			    	if(num === 0) {
			    		// leadership
						if(item.level === 0) {									    	
							return "valign='middle' class='leadership1'";
						}						
			    	}
			    	else if(num === 1){
			    		if(item.level === 0) {									    	
							return "class='leadership2'";
						}
			    	}
			    	return "";			    	
			  	}
			});										
		}
	
		ws.cr.util.generatePagination("pagination", pageResult.total, defaultResultsValue, "#switchpage", currentPage, 				
		
			function() {														
				var id = this.getAttribute('class');
					var regex = /^page_(.*)$/;
	        		var pageNumber = regex.exec(id)[1];
					navigateTo(pageNumber);				
					return false;
				}			
			);			
		}
}	
