
var cwdLazyBear={};

cwdLazyBear.webservice=(function(oOptions) {
    // Private members
    var _aRepsList=null;
    var _aCompaniesList=null;
    var _aCountryList=null;
    var _strCountries="{}";
    var _aStateList=null;
    var _strStates="{}";
    var _aProductList=null;
    var _strProducts="{}";     
    
    var _loadRepsList=function(fCallBack)
    {
    	var fFunc=function(oData)
    		{
     			_aRepsList=oData;
     			
     			if(fCallBack)
    				fCallBack(oData);
    		};
 
    	$.get("fetchData.jsp", { mode: "reps", fields: "lastname,firstname,email,repid" },fFunc,"json");	
    };
    
    var _loadCompaniesList=function(fCallBack)
    {
    	var fFunc=function(oData)
    		{
     			_aCompaniesList=oData;
     			
     			if(fCallBack)
    				fCallBack(oData);
    		};
 
		var strFields="companyname,id,address1,address2,city,stateid,statename,stateabbreviation,";
		strFields=strFields+"postalcode,countryid,countryname,countryabbreviation,otherstate,othercountry,phone,fax,siteurl,email";
		$.get("fetchData.jsp", { mode: "companies", fields: strFields },fFunc,"json");
	};    
    
    var _loadCountryList=function()
    {
    	var fFunc=function(oData)
    		{
    			_aCountryList={};
    			_strCountries="";
    			var fLoad=function(i,o)
    			{
    				_strCountries=_strCountries+" 'id_"+o.id+"': '"+o.name.replace(/'/g,"\\'")+"',";
    			};
    			
				_aCountryList=oData;
    			$.each(_aCountryList,fLoad);
    			_strCountries="{"+_strCountries.substr(0,_strCountries.length-1)+"}";
    		};
 
    	$.get("fetchData.jsp", { mode: "countries", fields: "id,name" },fFunc,"json");	    
    };
    
     var _loadStateList=function()
    {
    	var fFunc=function(oData)
    		{	
    			_aStateList={};
    			_strStates="";
    			var fLoad=function(i,o)
    			{
    				_strStates=_strStates+" 'id_"+o.id+"': '"+o.abbreviation+"',";
    			};
    			
				_aStateList=oData;
    			$.each(_aStateList,fLoad);
    			_strStates="{"+_strStates.substr(0,_strStates.length-1)+"}";
    		};
 
    	$.get("fetchData.jsp", { mode: "states", fields: "id,name,abbreviation" },fFunc,"json");	    
    };
 
    var _loadProductList=function()
    {
    	var fFunc=function(oData)
    		{
    			_aProductList={};
    			_strProducts="";
    			var fLoad=function(i,o)
    			{
    				_strProducts=_strProducts+" 'id_"+o.id+"': '"+o.name+"',";
    			};
    			
				_aProductList=oData;
    			$.each(_aProductList,fLoad);
    			_strProducts="{"+_strProducts.substr(0,_strProducts.length-1)+"}";
    		};
 
    	$.get("fetchData.jsp", { mode: "products", fields: "id,name" },fFunc,"json");	    
    };
    
    var _findState=function(iID)
    {
    	for(o in _aStateList)
    	{
    		if(o.id==iID)
    			return o;
    	}
    	
    	return null;
    };
        
    var _saveData=function(strValue, settings)
    {
    	var a=this.id.split("_");
        
        var fFunc=function(oData)
        	{
        		if(!oData[0].success)
        			alert("an error occured while updating. please contact administrator");
        	};
        $.get("saveData.jsp", { mode: "update", table: a[0], field: a[1], id: a[2], value: strValue },fFunc,"json");
        return(strValue);
	};
	
    var _saveSelectData=function(strValue, settings)
    {
    	var a=this.id.split("_");
        var fFunc=function(oData)
        	{
        		if(!oData[0].success)
        			alert("an error occured while updating. please contact administrator");
        	};
        $.get("saveData.jsp", { mode: "update", table: a[0], field: a[1], id: a[2], value: strValue.replace("id_","") },fFunc,"json");
        
        var oValues=eval("["+settings.data+"]");
        oValues=oValues[0];
        
        for(o in oValues)
        { 	
        	if(strValue==o)
        	{
        		strValue=oValues[o];
        		break;
        	}
        }
        
        return(strValue);
	};
	
	var _saveRepReceiveEmail=function(iID,blnReceive)
	{
		var fFunc=function(oData)
		{
			if(!oData[0].success)
				alert("an error occured while updating. please contact administrator");
		};
		
        $.get("saveData.jsp", { mode: "update", table: "repregion", field: "receiveemail", id: iID, value: (blnReceive?"T":"F") },fFunc,"json");
	};
	
	var _removeData=function(strMode,oDiv)
	{
		var fFunc=function(oData)
		{
			if(oData[0].success)
				oDiv.hide();
			else
				alert("an error occured while removing data. please contact administrator");
		};
		
		var oData={ mode: strMode };
		
		for(var i=2;i<arguments.length;++i)
		{
			jQuery.extend(oData, arguments[i] );
		}
		
        $.get("removeData.jsp", oData,fFunc,"json");
	}
	
    var _assignEditables=function()
    {
        $(".repEditable").editable(_saveData, {
            indicator : "Saving...",
            tooltip   : 'Click to edit...',
            cancel    : 'Cancel',
            submit    : 'OK',
            style     : "display: inline",
            width     : 100
        });
        
        $(".repEditableProduct").editable(_saveSelectData, { 
			data : _strProducts,
    		type   : "select",
    		tooltip   : 'Click to edit...',
            cancel    : 'Cancel',
            style     : "display: inline",
    		submit : "OK" 
		});

        $(".repEditableState").editable(_saveSelectData, { 
			data : _strStates,
    		type   : "select",
    		tooltip   : 'Click to edit...',
            cancel    : 'Cancel',
            style     : "display: inline",
    		submit : "OK" 
		});	

        $(".repEditableCountry").editable(_saveSelectData, { 
			data : _strCountries,
    		type   : "select",
    		tooltip   : 'Click to edit...',
            cancel    : 'Cancel',
            style     : "display: inline",
    		submit : "OK" 
		});
        
        $(".repEditableReceiveEmail").bind("click", { saveFunc: _saveRepReceiveEmail } ,function(event) {
        	event.data.saveFunc(this.value, this.checked);
		});	
        
        $(".removeRepClass").bind("click",function(event)
        		{
        			if(confirm("Are you sure you want to remove this rep and all of their associated coverage data?"))
        			{
        				var a=this.id.split("_");
        				_removeData("rep",$(this.parentNode.parentNode.parentNode),{ repID: a[1]})
        			}
        		}); 
    };

    return { // Public members.
    	initialize: function()
    	{
    		_loadCountryList();
    		_loadStateList();
    		_loadProductList();
    	},
    	
    	addData: function(oData,fCallBack)
    	{
    		jQuery.extend(oData, { mode: "add" });
    		$.get("saveData.jsp", oData ,fCallBack,"json");
    	},
    	
    	getStates: function()
    	{
    		return _aStateList;
    	},
    	
    	getCountries: function()
    	{
    		return _aCountryList;
    	},

    	getProducts: function()
    	{
    		return _aProductList;
    	},  
    	
    	getCompanies: function()
    	{
    		return _aCompaniesList;
    	},
    	
    	loadCompanies: function(fCallBack)
    	{
    		_loadCompaniesList(fCallBack);
    	},
    	
    	getReps: function()
    	{
    		return _aRepsList;
    	},
    	
    	loadReps: function(fCallBack)
    	{
    		_loadRepsList(fCallBack);
    	},
    	
		showReps: function() 
		{
		    var fGo=function(data)
		    {
		      var strTemp=$("#repTemplate").html();
		      $("#dataDiv").html("");
		      var fApply=function(i,o)
		        {
		          $("#dataDiv").append($.format(strTemp,(i % 2),o.lastname,o.firstname,o.email,o.repid));
		        };
		
		      $.each(data,fApply);		
		      _assignEditables();
		      
		      //var getRepDetail=;		
		      $(".showCompanyAssocDetailClass").click(function(){
		    	  $("#detailDiv").html('<img style="margin: 10px auto;" src="http://www.lazybeardesigns.com/images/indicator_snake.gif"/>');
		    	  var iID=this.id.replace("repCompanyAssocDetail_","");
		    	  var fSetDetail=function(oDetailData)
		    	  {
		    		  var strDetailTemp=$("#repDetailCompanyAssocTemplate").html();
		    		  $("#detailDiv").html("");
		    		  
		    		  var fApply=function(i,o){
				      		$("#detailDiv").append($.format(strDetailTemp,(i % 2),o.repid,o.id,o.companyname,o.stateabbreviation,o.countryname));
				    	};
				    	
				    	$.each(oDetailData,fApply);
				        
				        $(".removeCompanyAssocClass").bind("click",function(event)
				        	{
								if(confirm("Are you sure you want to remove this company association for this rep?"))
								{
									var a=this.id.split("_");
									_removeData("repcompanyassoc",$(this.parentNode),{ repID: a[1], companyID: a[2] } );
								}
				        	});		    	  
		    	  }
		    	  
		    	  $.get("fetchData.jsp", { mode: "companiesforrep", repID: iID, fields: "repID,id,companyname,stateabbreviation,countryname" },fSetDetail,"json"); 
		      });
		      
		      $(".showDetailClass").click(function(){
		    		$("#detailDiv").html('<img style="margin: 10px auto;" src="http://www.lazybeardesigns.com/images/indicator_snake.gif"/>');
					var iID=this.id.replace("repDetail_","");
					var fSetDetail=function(oDetailData)
					  {
					    var strDetailTemp=$("#repDetailTemplate").html();
					    $("#detailDiv").html("");
					    var aLocations={};
					    
					    var fSortProducts=function(i,o)
					    	{
					    		var str=o.countryname;
					    		
					    		if(str!="")
					    		{
							    	if(!aLocations[str])
							    		aLocations[str]=new Array();
	
							    	aLocations[str][aLocations[str].length]=o;
					    		}
							};
							
						$.each(oDetailData,fSortProducts);
						$("#detailDiv").html(" ");
						
						var fApply=function(i,o){
					      		$("#detailDiv").append($.format(strDetailTemp,(i % 2),o.productname,o.countryname,o.stateabbreviation,o.region,(o.receiveemail=="t")?"checked":"",o.repid,o.repregionid));
					    	};
						
						for(oLocal in aLocations)
						{
							$("#detailDiv").append("<div style=\"font-weight: bold;\">"+oLocal+"</div>");
							$("#detailDiv").append($("#repDetailHeaderTemplate").html());
							$.each(aLocations[oLocal],fApply);
						}
						
				        $(".removeRepRegionClass").bind("click",function(event)
					        	{
									if(confirm("Are you sure you want to remove this region/territory coverage for this rep?"))
									{
										var a=this.id.split("_");
										_removeData("repregion",$(this.parentNode.parentNode),{ repID: a[1] } );
									}
					        	});

					};
					$.get("fetchData.jsp", { mode: "reps", repID: iID, fields: "producttypeid,productname,receiveemail,countryname,stateabbreviation,region,repregionid" },fSetDetail,"json");
		        });
		
		    };
		    
		    _loadRepsList(fGo);
		},

		showCompanies: function()
		{
		  var fFunc=function(oData)
		  {
			  var strTemp=$("#repCompanyTemplate").html();
			  $("#dataDiv").html("");
			  $("#detailDiv").html(" ");
		
		      $.each(oData,function(i,o)
		        {
		          $("#dataDiv").append(jQuery.format(strTemp,(i % 2),o.id,o.companyname,o.address1,o.address2,o.city,o.stateid,o.statename,o.stateabbreviation,
		        		  o.postalcode,o.countryid,o.countryname,o.countryabbreviation,o.otherstate,o.othercountry,o.phone,o.fax,o.siteurl,o.email));
		        });
		        
		        $(".showDetailClass").click(function()
		        	{
		        		$("#detailDiv").html('<img style="margin: 10px auto;" src="http://www.lazybeardesigns.com/images/indicator_snake.gif"/>');
		        		var strDetailTemp=$("#companyRepDetailTemplate").html();
						var iID=this.id.replace("repCompanyDetail_","");
						var fSetDetail=function(oDetailData)
							{
								$("#detailDiv").html(" ");
								var fApply=function(i,o)
									{
										$("#detailDiv").append(jQuery.format(strDetailTemp,(i % 2), o.firstname, o.lastname, o.countryname, o.stateabbreviation, o.region));
									};
								$.each(oDetailData,fApply);
							};
						
						$.get("fetchData.jsp", { mode: "companyreps", companyID: iID, fields: "a.firstname, a.lastname, a.countryname, a.stateabbreviation, a.region" },fSetDetail,"json");
		        	});
		  	_assignEditables();
		  };

		  _loadCompaniesList(fFunc);
		  
		}
    };
});

