//+++++++++++++++++++++FROM PENDING GRID++++++++++++++++++
function ajaxImportListingsFileUpload()
	{
		$("#loading").show();
		$("#ajaxStatus").show();
		$.ajaxFileUpload
		(
			{
				url:'ImportCSVAction.do?action=importALCSV',
				secureuri:false,
				fileElementId:'fileToUpload',
				dataType: 'json',
				success: function (data, status)
				{
					if(typeof(data.error) != 'undefined')
					{
						if(data.error != '')
						{
							$("#ajaxErrorStatus").show();
							$("#ajaxErrorStatus").html(data.error);
						}else{
							$("#ajaxErrorStatus").show();
							$("#ajaxErrorStatus").html(data.msg);
						}
					}

					$("#loading").hide();
					if(typeof(data.MAINERROR) == 'undefined'){
						$("#ajaxMsgStatus").show();
						if(data.COUNT != "0"){
							$("#pendingListing").show();							
							$("#ajaxMsgStatus").html("You have successfully imported (" + data.COUNT + ") Listings.");
						}else{
							$("#ajaxMsgStatus").html("0 Listings were Imported.");
						}
						if(data.COUNTFAILED != "0"){
							var erorrs = "";
							$.each(data.ERRORS,function(index,value){								
								erorrs = erorrs +  value + " <br/> ";
			 				});	
						$("#ajaxErrorStatus").show();						
						$("#ajaxErrorStatus").html("Failed Listings (" +  data.COUNTFAILED + ") due to followings errors: - <br/>" + erorrs );
						}
					}else{
						$("#ajaxErrorStatus").show();						
						$("#ajaxErrorStatus").html("<b>Error : </b> " + data.MAINERROR);
					}
				},
				error: function (data, status, e)
				{
					$("#ajaxErrorStatus").show();
					$("#ajaxErrorStatus").html(e.toString());
					$("#loading").hide();
				}
			}
		)
	
		return false;

	}

function importListings(){
	resetGridAction();
	
	$("#importListingsDialogDiv").dialog("open");
}
function buildImportListingsDialog(){
	$("#importListingsDialogDiv").dialog({
			title:'Import Listings',
			//position:['middle','top'],
			width:520,
			height:300,
			autoOpen:false,
			buttons: { 
				"Close": function() {
					 $(this).dialog("close");
					 location.href="pending.jsp";
				},
				"Import": function() {
					$("#loading").hide();
					$("#ajaxStatus").html("");
					$("#ajaxMsgStatus").hide();
					$("#ajaxErrorStatus").hide();	
					$("#ajaxMsgStatus").html("");
					$("#ajaxErrorStatus").html("");	
					ajaxImportListingsFileUpload();
				}
			},
			modal: true, 
			overlay: { 
				opacity: 0.5, 
				background: "black"
			},
			open: function(event, ui) {
                $("#loading").hide();
				$("#ajaxStatus").html("");
				$("#ajaxMsgStatus").hide();
				$("#ajaxErrorStatus").hide();	
				$("#ajaxMsgStatus").html("");
				$("#ajaxErrorStatus").html("");	
			}
	});	
}

//+++++++++++++++

	//+++++++++++++++++++FROM LISTED GRID+++++++++++++++++++++++++++
	function toggleByDivId(divId){
		$("#"+ divId).slideToggle(600);     			
	}
	function setupReviseListingBulkDialog(){
		$("#reviseListingsBulkDialog").dialog({
			title:'Bulk Revise Active Items',
			position:['center','top'],
			width:700,
			autoOpen:false,
			buttons: { 
				"Close": function() {
					 $(this).dialog("close");
				},
				"Revise Items": function() { 
					var priceEntered = $("#priceTxt").val();
					var listingType = $("#listingTypeHidden").val();
					var durationSelected = "";
                    resetError();
                    setRevisionStatus("inProgress");
					//get duration from the dropdown shown on the ui in dialog
					if($("#listingTypeHidden").val() == "FIXED_PRICE_ITEM"){
						durationSelected = $("#fixedDurationSelect").val()
					}else{
						durationSelected = $("#chineseDurationSelect").val()
					}

					var url = "ListingEditAction.do?postedAction=reviseBulkAjax&listings="+ getSelectedRows();
				    var formData = $('#bulkReviseForm').serializeArray();
					$.getJSON(url , formData, function(JSONArray){ 
						$.each(JSONArray, function(index,JSON){
                            if(JSON.mainError){
                                status = JSON.mainError;
                                $("#responseDiv").addClass("dialogErrorStyle");
                                $("#responseDiv").html(status);
                                setRevisionStatus("reset");
                                return false;
                            }else{
                                var listingSeq = JSON.LISTINGSEQ;
                                var status = "<img src='images/tick1.png' title='"+ JSON.STATUSMESSAGE +"'/>"
                                if(JSON.STATUS == "FAILURE"){
                                    status = "<img src='images/cross.png' title='"+ JSON.STATUSMESSAGE +"'/>"
                                }
                                $("#"+ listingSeq +"revisionStatus").html(status);
                            }
						});
					});
				}
			},
			modal: true, 
			overlay: { 
				opacity: 0.5, 
				background: "black"
			}, 
			open: function(event, ui) {
                resetRevisionForm();
				populateReviseBulkListings();
			}
		});		
	}

    function setRevisionStatus(statusType){
        var selectedIds = getSelectedRows();
        var status;
        if(statusType=='inProgress'){
            status = "<img src='images/ajaxCircle.gif' />Revising";
        }else if(statusType=='reset'){
            status = "--";
        }

        $.each(selectedIds, function(index){
			$("#"+ selectedIds[index] + "revisionStatus").html(status);
        }); 
    }

    function resetRevisionForm(){
        $("#bulkReviseForm")[0].reset(); 
        resetPrice();
        resetDurations();
        resetError();
    }

    function resetError(){
        $("#responseDiv").html("");
        $("#responseDiv").removeClass("dialogErrorStyle");
    }
	
    /**
     * Returns true if all selected listings for revision are of same listing type, false otherwise.
     */
    function validateBulkRevise(){
        var items = getSelectedRowsData();
        var listingType = "";
        var validated = true;

        $.each(items, function(index){
            var itemObj = items[index].cell;
            if(listingType != ""){
                if(listingType != itemObj.listingType){
                    /*
                    $("#selectedListingsTable").append("You selected Listings that are a mix of Auction Type and Fixed Price Type. Bulk Revise only works on Items that are all of same Listing Type. Please reselect your items and try again.");
                    $("#reviseListingFormDiv").hide();
                    */
                    validated = false;
                }
            }
            listingType = itemObj.listingType
        });
        return validated;
    }

	function populateReviseBulkListings(){
        $("#selectedListingsTable").html("");
        var selectedRows = getSelectedRows(); 
        var items = getSelectedRowsData();
        var listingType = "";
        $.each(items, function(index){
            var itemObj = items[index].cell;
            listingType = itemObj.listingType;
        });
        
        $("#reviseListingFormDiv").show();
        var divStr = '<table id="tble" border="0"><tr style="background:#E8E8E8"><td width="90">Item # </td><td width="400">Title</td><td width="62">Duration</td><td width="60">BIN Price</td><td width="60">Status</td></tr>';
        $("#selectedListingsTable").append(divStr);
        $.each(items, function(index){
            var itemObj = items[index].cell; 
            divStr = "<tr>";
            divStr += 	"<td>"+ itemObj.itemNo +"</td>";
            divStr += 	"<td>"+ itemObj.title +"</td>";
            divStr += 	"<td>"+ itemObj.duration +"</td>";
            divStr += 	"<td>"+ itemObj.buyItNowPrice +"</td>";
            divStr += 	"<td style='text-align:center;' id="+ itemObj.id + "revisionStatus>--</td>";
            divStr += "</tr>";
            $("#tble").append(divStr);
            $("#selectedListingsTable").append("</table>");
            
            //duration dropdowns as per the slected type of listings
            $("#listingTypeHidden").val(listingType);
            if(listingType =="FIXED_PRICE_ITEM"){
                $("#chineseDurationSelect").hide();
                $("#fixedDurationSelect").show();
            }else{
                $("#fixedDurationSelect").hide();
                $("#chineseDurationSelect").show();
            }			
        });
		$("#reviseListingsBulkDialog" ).dialog( "option", "title", 'Revise Active Listings - (' + items.length + ') Listings Selected');
	}
	function resetPrice(){
            $("#priceTxt").attr('value',"");
            $("#priceTxt").attr('disabled',"true");
        }

        function resetDurations(){
            $("#fixedDurationSelect").attr('disabled',"true");
            $("#chineseDurationSelect").attr('disabled',"true");
        }


        function bindRevisionOptions(){
            $("#revisePrice").bind("click",function(e){
                if($("#revisePrice").attr('checked')){
                    $("#priceTxt").removeAttr('disabled');
                }else{
                    resetPrice();
                }
            });

            $("#reviseDuration").bind("click",function(e){
                var listingType = $("#listingTypeHidden").val();
                //select the right duration field based on listing type
                var durationFieldSelect;
                if(listingType == "FIXED_PRICE_ITEM"){
                    fieldName = "#fixedDurationSelect";
                }else{
                    fieldName = "#chineseDurationSelect";
                }

                if($("#reviseDuration").attr('checked')){
                    $(fieldName).removeAttr('disabled');
                }else{
                    $(fieldName).attr('disabled',"true");
                }
            });
        }
		function buildRelistingRuleDialog(){
		$("#relistingRuleDiv").dialog (
			{
			buttons: 
			   { 
				   " Close ": function(){ 
                    	$(this).dialog("close");
					},
					" Submit ": function()
				   { 
					 setRelistingRuleOnListings();
	     	  	   }
			   },
			   autoOpen : false,
			   title : "Set/UnSet Relisting Rule",
			   width:550,
			   height:500,
			   modal: true, 
               overlay: 
			   		{ 
                        opacity: 0.5, 
                        background: "black"
                    }  
			   
		   	}); 	
		}
	
        function relistingRule(){
			if(validateAction(true)){
				 var selectedRowsData = getSelectedRowsData();
				 var selectedIds = getSelectedRows();
				 populateRelistingRules(selectedRowsData, selectedIds);
			}
			resetGridAction();
		}
		function populateRelistingRules(selectedRowsData,selectedIds){
			var rowData = selectedRowsData;
			$("#relistingRuleDiv").dialog("open");	
			$("#relistingRuleDiv").html("");	
			$("#relistingRuleDiv").append("<img src='images/ajaxCircle.gif' /> <label class='ajaxStatus'>Loading Relisting Rules... </label>");
			$.getJSON("ListingEditAction.do?postedAction=getRelistingRules&listingSeqs=" + selectedIds, function(JsonArr){ 	
			$("#relistingRuleDiv").html("");  
				$.each(selectedRowsData, function(index){
					 html = layoutRelistingForm(rowData[index].cell);
					 $("#relistingRuleDiv").append(html);  
					 var html1= populateDropDown(JsonArr[0]);		
					 $("#relistingRules" + rowData[index].cell.id).append(html1);
			 	});
			 	$.each(JsonArr[1], function(key,value) {
					$("#relistingRules" + key).val(value);
				});
				
		 });
	}
		
		function layoutRelistingForm(itemRow){
			var title = "undefined";
			if(itemRow.titleOnly != ""){
				title = itemRow.titleOnly;	
			}
			var json =  "";
			var url = "ListingEditAction.do?postedAction=getRelistingRules"; 
			var html = "";			
			html += 	"<fieldset id=\"launchScheduleFieldSet\" style=\"border-color:white; margin-bottom:10px;\">";
			html += 		"<legend>Title - "+ title +"</legend>";
			html +=             "<form action=\"VieListw.do\" name=\"RelistingOptionForm"+ itemRow.id +"\" id='RelistingOptionForm"+  itemRow.id +"' method='post'>";
			
			html +=	                    "<input type=\"hidden\" name=\"listingSeq\"  id=\"listingSeq\" value=\""+ itemRow.id +"\">";
			html +=                           "<label class=\"oneFonts\" style=\"width:100px; clear:left; margin-left:5px;\">";
			html +=                                "Relisting Rules: </label>";
			html +=								"<select name='relistingRules' id=\"relistingRules"+ itemRow.id +"\" class='relistingRules' styleClass='one'>";		
			html +=								"</select>"		
			html += 					"<label id='statusMessage"+ itemRow.id +"' style='margin-left:10px; width:300px;font-size:12px;font-weight:bold;'></label>"
			html +=  		 	"</form>";
			html +=   "</fieldset>";
			
			return html;
		}
		
		function setRelistingRuleOnListings(){
			var url = "ListingEditAction.do?postedAction=applyRelistingRule";
			var selectedIds = getSelectedRows();
			 $.each(selectedIds, function(index){				
				var formData = $('form[name=RelistingOptionForm'+ selectedIds[index] +']').serializeArray();
				$("#statusMessage"+selectedIds[index]).css("color","black");
				$("#statusMessage"+selectedIds[index]).html("<img src='images/ajaxCircle.gif' /> <label class='ajaxStatus'>Applying Relisitng Rule in process... </label>");
				$.getJSON(url,formData, function(response){					
					$("#statusMessage"+selectedIds[index]).html(response.MESSAGE);
					if(response.STATUS == "Success"){
						$("#statusMessage"+selectedIds[index]).css("color","green");
					}else{
						$("#statusMessage"+selectedIds[index]).css("color","red");
					}
				});
			});//for each selected listing
		}	
	//++++++++++++++++++++ACTIONS FOR TRANSACTION GRID+++++++++++++++
	function synchronizeTransactionsAction(){
				resetGridAction();
				hideAllTransDivs();
				hideAllDialogButtons();
				ShowHideDialogButton("Synchronize Sales History",1);
				$('#dialogBox').dialog("option" , "width" , 400);
				$('#dialogBox').dialog("option" , "height" , 250);
				$('#dialogBox').dialog("option" , "title" , "Synchronize Sales History");
				$('#dialogBox').dialog("option" , "position" , ['center','top']);
				$("#dialogBox").dialog("open");
				$("#synchronizeSalesHistory").show();
	}
	function SubmitSynchronizeSalesHistoryAction(){
			$("#ajaxStatus").text("Now Synchronizing Sales History...");
			$("#synchLoading").show();	
			$.post("SynchronizeItemsAction.do?action=importTransactions", function(response){ 
					  $("#synchronizeSalesHistory").html(response);
					  $("#ajaxStatus").html("Import process finished");
					  $("#synchLoading").hide();	
					  
			});

	}
	function printShippingLabel(){//First method called for generating shipping labels
		if(validateAction(true)){
			 var selected = getSelectedRows();
			 loadShipmentLabelsForms(selected);
		}
		resetGridAction();
		
	}
   	function enterShippingDetails(){
		if(validateAction(true)){
			 var selected = getSelectedRows();
			 loadShippingInfoForm(selected);
		}
		resetGridAction();
	}
	function loadShipmentLabelsForms(selectedTransSeqs){//shows up dialog to geneate shipping labels.
		selectedTrans = selectedTransSeqs;
		hideAllTransDivs();
		hideAllDialogButtons();
		ShowHideDialogButton("Request Endicia Label",1);
		$('#dialogBox').dialog("option" , "width" , 900);
		$('#dialogBox').dialog("option" , "height" , 400);
		$('#dialogBox').dialog("option" , "title" , "Generate Shipping Labels for selected sales");
		$('#dialogBox').dialog("option" , "position" , ['center','top']);
		$("#dialogBox").dialog("open");
		

		$("#generateShippingLabel").show();	
		$("#infoForms").html("");
		$("#infoForms").html("Loading shipment label generation forms...<img src='images/ajaxCircle.gif' />");
		var url = "ShippingInfoAction.do?action=generateHTML&transactionSeq="+ selectedTransSeqs  ; 
		$.getJSON(url, function(JSONArray){ 					
			$("#infoForms").html("");
			$.each(JSONArray, function(index,JSON) {
				if(JSON.RESPONSETYPE == "pending"){
					var formHTML = getShipmentLabelFormHTML(JSON);
					$("#infoForms").append(formHTML);
				}else{
					$("#infoForms").append(getShipmentLabelsGeneratedHTML(JSON));	
				}
			});
			
	
		});  
	}
		   
	function getShipmentLabelsGeneratedHTML(JSON){//produces HTML block to show labels already generated
		var str = "";
			if(JSON.RESPONSETYPE == "noEndicia"){
				str += "<Div class='errorStyle'>"+JSON.MESSAGE +"</Div><BR>";
			}else{
			
				str += '<Div id="ShipmentLabelFormDiv'+ JSON.TRANSACTIONSEQ +'">';
						str += '<fieldset style="border-color: #ffffff;">';
	
							str += '<legend>Item - '+ JSON.ITEMTITLE +" ("+JSON.ITEMNUMBER +') </legend>';
							str += '<Div style="width:100%; margin-bottom:4px;">';
								str += '<span id="leftSpan">';
									str += '<label class="lbl">Tracking Number: </label>';
									str += '<label><font style="font-weight:normal">'+ JSON.TRACKINGNUMBER +'</font></label>';
								str += '</span>'
								str += '<span id="rightSpan" style="left:0px;">'
										 str += '<label class="lbl" style="width:80px;float:left;">Label: </label>';
										 str += '<label ><font style="font-weight:normal">'+ " <a class='smalllinkgrey' href="+ JSON.IMAGEPATH +" target='_blank'>Click to see Label</a>" +'</font></label>';			
								str += '</span>';
								str += '</Div>';
							str += '</fieldset>';
				str += '</DIV>';
			}
		return str;
	}
	
	function getShipmentLabelFormHTML(JSON){//produces HTML block to show form to crate shipping labels
		var str = "";
		str += '<Div id="ShipmentLabelFormDiv'+ JSON.TRANSACTIONSEQ +'">';
			str += '<form action="/ShippingInfoAction.do?action=generateShippingLabel" method="post" id="ShippingInfoForm'+ JSON.TRANSACTIONSEQ +'">'
			str += '<input type="hidden" id="transactionSeq" name="transactionSeq" value="'+ JSON.ITEMNUMBER +'" />';
			str += '<input type="hidden" id="itemNumber" name="itemNumber" value="'+ JSON.ITEMNUMBER +'" />';
			str += '<br><br>';
				str += '<fieldset style="border-color: #ffffff;">';
					str += '<legend>Item - '+ JSON.ITEMTITLE +" ("+JSON.ITEMNUMBER +') </legend>';
					str += '<Div style="width:100%; margin-bottom:4px;">';
						str += '<span id="leftSpan">';
							str += '<label class="lbl">From Address: </label>';
							str += '<label><font style="font-weight:normal;font-size:11px;">'+ JSON.FROMADDRESS +'</font></label>';
						str += '</span>'
						str += '<span id="rightSpan" style="left:0px;">'
								 str += '<label class="lbl" style="width:80px;float:left;">To Address: </label>';
								 str += '<label ><font style="font-weight:normal;font-size:11px">'+ JSON.TOADDRESS +'</font></label>';			
						str += '</span>';
					str += '</Div>';
					str += '<Div style="width:100%; margin-left:20px;">';
						str += '<span style="width:100px; display:block; float:left">';
								str += '<label class="lbl">Insured <br>';
								str += '<input type="checkbox" name="isInsured" id="isInsured"/>';
									str += '</label>';
						str += '</span>';
						str += '<span style="width:120px; display:block; float:left">';
								str += '<label class="lbl">Insured Value:<br /></label>';
								str += '<input type="text" name="insuredValue" id="insuredValue" size="10"/>';		
						str += '</span>';
						str += '<span style="width:220px; display:block; float:left">';
							str += '<label class="lbl">USPS Mail Class:<br />';
								str += "<select id='mailClass' name='mailClass' onchange='changeMailClassDropDown("+ JSON.TRANSACTIONSEQ +");'>"
									str += getDropDownOptions(JSON.MAILCLASSES);
								str += "</select>"
								str += '<span class="requiredStar"> *</span></label>';
						str += '</span>';
						str += '<span style="width:120px; display:block; float:left">';
							str += '<label class="lbl">Weight Oz:</label><br />';
							str += '<input type="text" name="weightOZ" id="weightOZ" size="10"/><label class="requiredStar"> *</label>';
						str += '</span>';
						
						str += '<span style="width:150px; display:none; float:left" id="sortTypeSpan">';
							str += '<label class="lbl">Sort Type:<br />';
								str += "<select id='sortType' name='sortType'>"
									str += getDropDownOptions(JSON.SORTTYPES);
								str += "</select>"
								str += '<span class="requiredStar"> *</span></label>';
						str += '</span>';
					   str += '</Div>';
				str += '</fieldset>';
			str += '</form>';
			str += '<DIV id="response" style="margin-left:10px"></DIV>'
		str += '</DIV>';
		return str;
	}
		  
	function getDropDownOptions(JSONArr){//gives back drop down options out of json array
		var div = "";
		for(var key in JSONArr){
				div += "<option name='"+ key +"' value='"+ key +"'>"+ JSONArr[key] + "</option>";
		}
		return div;
	}
	function populateDropDown(response){ 	
		var div = "";		
			$.each(response,function(key,value){					
				 div += "<option value='" + key + "'>" + value + "</option>";
			});			
		return div;
	}
		  
	function submitShippingLabelForm(transactionSeqsStr){ //call made to generate shipping labels
		
		var transactionSeqsArray = transactionSeqsStr.toString().split(",");
		$.each(transactionSeqsArray, function(index,seq) {
				var formData = $("#ShippingInfoForm"+ seq ).serialize();
				
				var url = "ShippingInfoAction.do?action=generateShippingLabel&transactionSeq="+ seq  ; 
				$("#ShipmentLabelFormDiv"+ seq +" #response").css("color","grey");
				$("#ShipmentLabelFormDiv"+ seq +" #response").html("Contacting Endicia Server, generating label...<img src='images/ajaxCircle.gif' />");
				$.getJSON(url,formData, function(JSON){ 	
					
					$("#ShipmentLabelFormDiv"+ seq +" #response").html(JSON.MESSAGE);
					if(JSON.RESPONSETYPE == "ERROR"){
						$("#ShipmentLabelFormDiv"+ seq +" #response").css("color","red");
					}else if(JSON.RESPONSETYPE == "SUCCESS"){
						$("#ShipmentLabelFormDiv"+ seq +" #response").css("color","blue");
						$("#ShipmentLabelFormDiv"+ seq +" #response").append(" <a class='smalllinkgrey' href="+ JSON.IMAGEPATH +" target='_blank'>Click to see Label</a>");
					}
				});
		});
	}
	function getCurrDate(){
		var d = new Date();
		var curr_date = String(d.getDate()) ;
		if (curr_date.length == 1) {
			curr_date = "0" + curr_date;
		}
		var curr_month = String(d.getMonth() + 1);
		if (curr_month.length == 1) {
			curr_month = "0" + curr_month;
		}
		var curr_year = 	d.getFullYear();
		var curr_hours = String(d.getHours());
		if (curr_hours.length == 1) {
			curr_hours = "0" + curr_hours;
		}
		var curr_minutes =  String(d.getMinutes());
		if (curr_minutes.length == 1) {
			curr_minutes = "0" + curr_minutes;
		}
		return curr_month + "/" + curr_date + "/" + curr_year + " " + curr_hours + ":" + curr_minutes +":00";
	}
	
		//-----------SHIPPING INFO FUNCTIONS HERE------------------------
		function loadShippingInfoForm(transactionSeqs){//loads shipping info forms
				selectedTrans = transactionSeqs;
				selectedLength = 1;
				if(selectedTrans.constructor.toString().indexOf("Array") != -1){
					selectedLength = selectedTrans.length;
				}
				hideAllTransDivs();
				hideAllDialogButtons();
				ShowHideDialogButton("Submit Shipping Information",1);;
				
				$("#dialogBox" ).dialog( "option", "title", 'Save Shipping Information - (' + selectedLength + ') Sales Selected');
				$('#dialogBox').dialog("option" , "position" , ['center','top']);
				$('#dialogBox').dialog("option" , "width" , 800);
				$('#dialogBox').dialog("option" , "height" , 400);

				$("#dialogBox").dialog("open");
				$("#submitShippingInfo").show();	
				$("#shipmentForms").html("");
				$("#shipmentForms").html("Loading shipment forms...<img src='images/ajaxCircle.gif' />");
				var url = "ShipmentAction.do?postedAction=generateHTML&transactionSeq="+ transactionSeqs ; 
				$.getJSON(url, function(JSONArray){ 					
						$("#shipmentForms").html("");
						$.each(JSONArray, function(index,JSON) {
							var formHTML = getShippingInfoFormHTML(JSON);							
							$("#shipmentForms").append(formHTML);						
							$("#ShippingInfoFormDiv" + JSON.TRANSACTIONSEQ + " .shipmentDate" + JSON.TRANSACTIONSEQ).datetimepicker();
							if(JSON.SHIPMENTDATE == ""){
								$("#ShippingInfoFormDiv" + JSON.TRANSACTIONSEQ + " .shipmentDate" + JSON.TRANSACTIONSEQ).val(getCurrDate());
							}
							$('#shipmentCourierTxt' + JSON.TRANSACTIONSEQ).limit('500');
							$('#trackingLinkTxt' + JSON.TRANSACTIONSEQ).limit('500');
						});
				});   
			   
		}
		   
		  function getShippingInfoFormHTML(JSON){//generated HTML forms to submit shipping infos
			var shipmentDate = "";
			var trackingNumber = "";
			var courier = "";
			var trackingLink = "";
			
			if(JSON.SHIPMENTDATE != null){ shipmentDate = JSON.SHIPMENTDATE; }
			if(JSON.TRACKINGNUMBER != null){ trackingNumber = JSON.TRACKINGNUMBER; }
			if(JSON.COURIER != null){ courier = JSON.COURIER; }
			if(JSON.TRACKINGLINK != null){ trackingLink = JSON.TRACKINGLINK; }

			var str = "";
			str += '<Div id="ShippingInfoFormDiv'+ JSON.TRANSACTIONSEQ +'" style="margin-left:5px;display:block;">';
				str += '<fieldset style="margin-top:6px; width:740px;">';
				str += '<legend>Item - '+ JSON.ITEMTITLE +" ("+JSON.ITEMNUMBER +') </legend>';				
					str += '<form name="shipmentForm'+ JSON.TRANSACTIONSEQ +'" action="/ShipmentAction.do?postedAction=saveShipmentDetails" method="post" id="shipmentForm'+ JSON.TRANSACTIONSEQ +'">';
					str += '<input type="hidden" name="transactionSeq" id="transactionSeq" value="'+  JSON.TRANSACTIONSEQ +'"/>';
					str += '<span style="width:128px;display:block; float:left">';
					
						str += '<label class="lbl">Shipment DateTime:</label><br />';
						str += '<input type="text" id="shipmentDate' + JSON.TRANSACTIONSEQ + '" name="shipmentDate" size="18" value="'+ shipmentDate +'" class="shipmentDate' + JSON.TRANSACTIONSEQ + '"/>';
						
						
						str += '<DIV style="margin-top:6px;width:650px;">';
							//str += '<label class="lbl" style="margin-top:4px;margin-left:10px;"><input type="checkbox" id="isCompletedOnEbay" name="isCompletedOnEbay" '+ JSON.ISCOMPLETEDONEBAY +' '+  readonly +'/>Completed on Ebay</label><br>';
							
							str += '<label class="lbl"><input type="checkbox" id="isNotify" name="isNotify" />Notify buyer about shipment</label>';

							var shippedDisabled="";
							if(JSON.ISSHIPPED == "checked"){
								shippedDisabled = "disabled";
							}
			str += '<label class="lbl" style="margin-left:20px;"><input type="checkbox" id="isShipped" name="isShipped" '+ JSON.ISSHIPPED +' '+ shippedDisabled +' checked />Mark Item as Shipped (Item Status will be updated on eBay)</label>';


						str += ' </DIV>';
					str += '</span>';
					str += '<span style="width:180px;display:block; float:left">';
						str += '<label class="lbl">Tracking Number:</label><br />';
						str += '<input type="text" maxlength="500" id="trackingNumber" name="trackingNumber" value="'+ trackingNumber +'" size="25"/>';
					str += '</span>';
			
					str += '<span style="width:180px;display:block; float:left">';
						str += '<label class="lbl">Shipment Service:</label><br />';
						str += '<input type="text" id="shipmentCourierTxt'+ JSON.TRANSACTIONSEQ + '" name="shipmentCourier" size="30"  value="'+ courier +'">';							
					str += '</span>';
					str += '<span style="width:160px;display:block; float:left">';
						str += '<label class="lbl">Tracking Link:</label><br />';
						str += '<input type="text" id="trackingLinkTxt'+ JSON.TRANSACTIONSEQ + '" name="trackingLink" size="40" value="'+ trackingLink +'"></label>';
					str += '</span>';
				   str += '<DIV id="response" style="margin-left:5px; clear:both;font-size:10px;"></DIV>'
				   str += '</fieldset>';
				   str += '</form>';
							  
					str += '</Div>';
			return str;
		  }
		    
	function SubmitShippingInfoForm(transactionSeqs){//submitting shipping info forms with this method			
			var transactionSeqsArray = transactionSeqs.toString().split(",");
			$.each(transactionSeqsArray, function(index,seq) {
					var formData = $("#shipmentForm"+ seq ).serialize();
					var url = "ShipmentAction.do?postedAction=saveShipmentDetails&transactionSeq="+ seq  ; 
					$("#ShippingInfoFormDiv"+ seq +" #response").css("color","grey");
					$("#ShippingInfoFormDiv"+ seq +" #response").html("<font style='font-size:10px;'>Saving shipment details...<img src='images/ajax-loader.gif' /></font>");
					$.getJSON(url,formData, function(JSON){ 	
						
						$("#ShippingInfoFormDiv"+ seq +" #response").html(JSON.MESSAGE);
						if(JSON.RESPONSETYPE == "FAILED"){
							$("#ShippingInfoFormDiv"+ seq +" #response").css("color","red");
							
						}else if(JSON.RESPONSETYPE == "SUCCESS"){
							$("#ShippingInfoFormDiv"+ seq +" #response").css("color","blue");
					
							var shipped = JSON.ISSHIPPED;
							if(shipped == 'true'){
								shipped = "Shipped"	;
							}else{
								shipped = "Not Shipped"	;
							}
							$("#shippingStatus"+ json.SEQ).html("Status: "+ shipped);	
							$("#shippingStatus"+ json.SEQ).css("font-color","red");	
						}
					});
			});
	}
	
	
	//+++++++++++++++++++++++++Transactions grid actions ends here++++++++++++++++++++++++++++
	function resetGridAction(){
			$("#gridAction").val('selectAction');
			document.getElementById('gridAction').refresh(); 
	}
	
	jQuery.download = function(url, data, method){
	//url and data options required
		if( url && data ){ 
			//data can be string of parameters or array/object
			data = typeof data == 'string' ? data : jQuery.param(data);
			//split params into form inputs
			var inputs = '';
			jQuery.each(data.split('&'), function(){ 
				var pair = this.split('=');
				inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
			});
			//send request
			jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
			.appendTo('body').submit().remove();
		};
	};

	function exportSalesHistoryCSV(){
					resetGridAction();
	 	  			$('#obj').val("transaction");
					var formData = $("#search_form").serializeArray();
					var implicitConditionsFormData = $("#implicitConditions_form").serializeArray();
					var counter = implicitConditionsFormData.length;
					$.each(formData,function(index,val){
						implicitConditionsFormData[counter++] = formData[index];
					}); 
					$.download('ExportListingsAction.do?action=exportSales',implicitConditionsFormData );
					
	}
	 
	
	function exportPendingListingsCSV(){
			jConfirm("Do you want to export the searched listings?","Confirm Listings Export",  function(r){
				if (r==true){    	
					$('#obj').val("listing");
					var formData = $("#search_form").serializeArray();
					var implicitConditionsFormData = $("#implicitConditions_form").serializeArray();
					var counter = implicitConditionsFormData.length;
					$.each(formData,function(index,val){
						implicitConditionsFormData[counter++] = formData[index];
					}); 
					$.download('ExportListingsAction.do?action=exportListings',implicitConditionsFormData );
			  	}
			});
			resetGridAction();
	}

	function reviseListing(){
		if(validateAction(false)){
            var selectedRows = getSelectedRows(); 
			location.href="ListingEditAction.do?postedAction=revise&type=revise&listing=" + selectedRows[0] ;
		}
		resetGridAction();
    }

	function reviseListingBulk(){
		if(validateAction(true)){
            if(!validateBulkRevise()){
                jAlert("You selected Listings that are a mix of Auction Type and Fixed Price Type. Bulk Revise only works on Items that are all of same Listing Type. Please reselect your items and try again.","Multiple Listing Types Found");
            }else{
                $("#reviseListingsBulkDialog").dialog("open");
            }
			//location.href="ListingEditAction.do?postedAction=revise&type=revise&listing=" + selectedRows[0] ;
		}
		resetGridAction();
    }
   
	
	 /**
      * Opens a selected listing for editing.
      */
    function editListing(){
	    doAction("edit",false);
    }
	
	function editListingTemplate(){
	    doAction("editTemplate",false);
    }

    function showPreview(remoteUrl){
        $.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'		    : 1100,
			'height'		: 600,
            'type'          : 'iframe',
			'href'			: remoteUrl
		});

        $("#fancybox-frame").load(function(){
            $.fancybox.hideActivity();
        });

        $.fancybox.showActivity();
        return false;
        
    }

    function doAction(actionName,isMultiListingAction){
        $.alerts.okButton = "Ok";
        if(validateAction(isMultiListingAction)){
			 var selected = getSelectedRows();
				 if(actionName == "listingPreview"){
					 showPreview("ListingEditAction.do?postedAction=listingPreview&listing="+ selected[0]);
					 resetGridAction();
				 }else if(actionName == "editTemplate"){
					 location.href="ListingEditAction.do?postedAction=edit&type=template&listing="+ selected[0];
				 }else{
					 location.href="ListingEditAction.do?postedAction=" + actionName + "&listing="+ selected;
				 }

		  }else{
			resetGridAction();
		}
    }

    function validateAction(isMultiListingAction){
		var selected = getSelectedRows();
		if(selected.length == 0){
			jAlert("You should select at least one listing for this Action.","Action Error"); 
			return false;
			resetGridAction();
		}else if((selected.length > 1) && !(isMultiListingAction)){
			jAlert("Multiple Listings Selected. Please select single listing for this Action.","Action Error");
			return false;
			resetGridAction();
		}else{
			return true;
		}
    }
    
    function handleListingPreview(){
        doAction("listingPreview",false);
    }
	function preview(){
        doAction("listingPreview",false);
    } 
    
	function archiveListing(seq){
        doAction("statusToArchive",true);
    }
	
	function createListing(){
        doAction("createNew",false);
    }
	
    function extractTemplate(){
	    if(validateAction(false)){
			var selectedRows = getSelectedRows(); 
			location.href="ListingEditAction.do?postedAction=extractTemplate&type=template&listing=" + selectedRows[0] ;
	    }else{
			resetGridAction();
		}
    }
	

    
    function copyListing(){
        doAction("extractTemplate",false);
    }
	
	function unarchiveListing(){
    	doAction("statusToUnArchive",true);
    }

    function showSearch(){
		$(".filterBody").css("visibility","visible");
		$(".filterBody").slideToggle(600);
		if($("#searchBtn").html() == "open"){
			$("#searchBtn").html("close");
		}else{
			$("#searchBtn").html("open");
		}
		$("form")[0].reset();
    }
	

	function handleGridAction(){
        var funcToCall = $("#gridAction option:selected").val();
	    if(!(funcToCall == "selectAction")){
		    return eval(funcToCall)();
	    }
	}

	function handleSortAction(){
        var fieldToSort = $("#sortAction option:selected").val();
	    if(!(fieldToSort == "selectSort")){
		    return setSortByField(fieldToSort);
	    }
	}

	function handleSortDirectionAction(){
        var directionToSort = $("#sortDirectionAction option:selected").val();
	    if(directionToSort == "desc"){
            directionToSort = "dsc";
	    }
        return setDirectionToSort(directionToSort);
    }

    function setDirectionToSort(sortDirection){
         $("#list2").flexOptions({newp:1,sortorder:sortDirection});
		 $("#list2").flexReload(); 
    }

    function setSortByField(sortField){
        Sortname = sortField;
         $("#list2").flexOptions({newp:1,sortname:sortField});
		 $("#list2").flexReload(); 
    }

	function addSelect(cellDiv,id){
		cellDiv.innerHTML = "<input type=\"checkbox\" id=\"select" +id + "\" name=\"check\" onclick=\"checkClicked("+id+")\">";
		/*
		  $('#row'+id).click
		(
			function ()
			{
				alert(this.innerHTML);
				if($("#select" + id).is(':checked')){
		             		$("#select" + id).attr('checked', false);
				}else{
		             		$("#select" + id).attr('checked', true);
				}
				return true;
			}
		); 
	 	*/	
	}
	//not used anymore, all launches will be bulk operations
	function launch(){
        doAction("launch",true);
    }
	function launchListing1(){
        doAction("launch",true);
    }
	function secondChanceListing(seq){
		if(validateAction(false)){
			var selected = null;
			var items = $('.trSelected');
			selected = items.children('td').eq(10).text();
			if(selected == "true"){
					var selectedSeq = getSelectedRows();
					location.href= 'ListingEditAction.do?postedAction=generateSecondChanceHtml&listing='+ selectedSeq,			'width=650,height=750,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,status=yes'
			}
		}
	 resetGridAction();
    }	
	

	function getSelectedRows(){
        var selected = [];
		var items = $('.trSelected');
		var itemlist;
		
		for(i=0;i<items.length;i++){						
			selected.push(items.children('td').eq(i*(columnCount+1)).text()); 						
		}; 
		return selected;
	}
	
	function getSelectedRowsData(){
		var selectedIds = getSelectedRows();
		var allRows = getGridDataJSON();
		var selectedRows = new Array() ;
		var i = 0;
		$.each(allRows, function(index){
			$.each(selectedIds,function(j){
				if(allRows[index].id == selectedIds[j]){
					selectedRows[i] = allRows[index];
					i++;
				}
			});
		});
		return selectedRows;
	}
	
	//not used anymore. All delete operatons are made bulk now
	function deleteListing1(){
	  if(validateAction(true)){
			jConfirm("Are you sure you want to delete the selected listings?","Confirm Delete Listings",  function(r){
				if (r==true){    	
			 	  var selectedRows = getSelectedRows();
				  location.href="ListingEditAction.do?postedAction=deleteListing&listing="+ selectedRows[0] + "&itemstatus=1";
			  	}
			});
        }
    }
	
	function deleteListing() {  // returns IDs of selected TRs	
        if(validateAction(true)){
			var selectedRows = getSelectedRows(); 
            $.alerts.okButton = "Yes";
            $.alerts.cancelButton = "No";
            jConfirm("Are you sure you want to delete the selected listings?","Confirm Delete Listings", function(r){
				if (r==true){    	
					 location.href="ListingEditAction.do?postedAction=deleteListingBulk&listings="+ selectedRows + "&itemstatus=1"  ;
				}else{
                    resetGridAction();
			    }
            });
        }else{
            resetGridAction();
        }
      }
	
	function checkClicked(id){
		 $('#row'+id).toggleClass('trSelected');
	}
	
	function selectAllChecked(){
		if ($('input[name=selectAllCheckbox]').is(':checked')){
			$("#list2 INPUT[type='checkbox']").attr('checked', true);
			var allItems = $('#list2')[0].rows ;
			for(i=0;i<allItems.length;i++){
				$('#'+ allItems[i].id +'').addClass('trSelected');
			}
		}else{
			$("#list2 INPUT[type='checkbox']").attr('checked', false);
			var allItems = $('#list2')[0].rows ;
			for(i=0;i<allItems.length;i++){
				$('#'+ allItems[i].id +'').removeClass('trSelected');
			}
		}
	}
	
	function goEbay(tex){
		window.open(tex,'mywindow','width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
    }
	
	function initGridActions(){
        enableFlexigrid();
		$(".btnDiv select").msDropDown({
            visibleRows:10}
        );
		$(".filterBody").hide();
	}
	
	
	function EndListingCall(endReason){
	 		 location.href="ListingEditAction.do?postedAction=endListing&endReason="+endReason+"&listing="+ endListingSeq ;
	}
	
	
	function endListing(){
		if(validateAction(false)){
			var selectedRows = getSelectedRows(); 
			endListingAction(selectedRows);
			resetGridAction();
	    }else{
			resetGridAction();
		}
	}
	var endListingType = "endListingType1";
	function endListingAction(seq){
		
		endListingSeq = seq;
		
		//Hiding both the divs
		$("#12HoursLeft").css("display","none");
		$("#12HoursNotLeft").css("display","none");
		
		//Extracting itemID from the grid and setting it on the dialog
		var items = getSelectedRowsData();
		itemId = items[0].cell.itemNo;
		//itemId = ($('#row'+seq +'').children('td').eq(3).text());
		
				$('#itemIdLabel').html("");
				$('#itemIdLabel').html('<label class=\"lblSimple\">Listing to End : '+ itemId +'</label><br>');
			
		
		//Ajax call to get how many hours left to end the listing
		$.post("ListingEditAction.do?postedAction=listingEndTimeLeft&listingSeq="+ seq , function(response){ 					
					hoursLeft = response;
					$("#loadingImage").hide();
					//Show/hide div as per hours left.
					if (parseInt(hoursLeft)  >= 12){
						endListingType = "endListingType1";
					   $("#12HoursLeft").css("display","block");
				    }else{
						endListingType = "endListingType2"
					   $("#12HoursNotLeft").css("display","block");
					}
					$("#HoursleftStr").html(hoursLeft);
					
					//Extracting bid count and enable/disable the options as per count
					bidCount = items[0].cell.bidCount;
					//bidCount = ($('#row'+seq +'').children('td').eq(9).text());
					if(parseInt(bidCount)==0){
							$("input[name='"+endListingType+"']").each(function(i) {
									if($(this).attr('value')=='sellToHighBidder'){
										$(this).attr('disabled', 'disabled');
										$(this).attr('checked', '');						
									}
									if($(this).attr('value')=='notAvailable'){
										$(this).attr('checked', 'checked');
									}
							});
					}else{
						$("input[name='"+endListingType+"']").each(function(i) {
								if($(this).attr('value')=='sellToHighBidder'){
									$(this).attr('disabled', '');
									$(this).attr('checked', 'checked');
								}
						});
					}
		});
		$("#dialog").dialog("open");
		$("#loadingImage").css("display","block");
			
	}
	
	function buildEndListingDialog(){
		$("#dialog").dialog ({
			buttons: 
			   { 
				   " Cancel ": function(){ 
						$(this).dialog("close");
					},
					" Ok ": function()
					{ 
							var endReason =	$("input[name='"+endListingType+"']:checked").val();
							if(endReason != null && endReason !=""){
								EndListingCall(endReason);
							}
							$(this).dialog("close"); 
					}
			   },
			   width:600,
			   modal: true, 
			   autoOpen:false,
			   overlay: 
					{ 
						opacity: 0.5, 
						background: "black"
					}  
			   
		}); 
	}
	
	function launchListing(){
		BulkOperation("launch");
		return false;
    } 

	function relistItem(){
        BulkOperation("relist");
		return false;
    }
	
	function verify(){
        BulkOperation("verify");
		return false;
    }

	//|||||||||||||||||||||BULK OPERATIONS METHODS HERE |||||||||||||||||||||||||||
	function BulkOperation(actionType){
		if(validateAction(true)){
			var selectedRows = getSelectedRows(); 
			var selectedRowsData = getSelectedRowsData();
			
			BulkListingsPopulateRows(selectedRowsData, actionType);
			if(actionType  == "launch"){
				BulkListingPopulateRemoveCopyListingRadios();	
			}
			BulkListingShowDialog(selectedRows, actionType);
			resetGridAction();
			$("#dialog").dialog("open");
	    }else{
			resetGridAction();
		}
		return false;		
	}
	function BulkListingPopulateRemoveCopyListingRadios(){
		$("#removeCopyListingsRadios").show();
	}
	
	function BulkListingsPopulateRows(selectedRowsData, actionType){
		var items = selectedRowsData;
		$('#listings').html("");
		$.each(items, function(index){
			var itemObj = items[index].cell; 
			itemSeq = itemObj.id;
			itemTitle = itemObj.title;
			
			var blockText = "";
			blockText  +=  "<Div id='itemBlock' style='margin-bottom:8px;'>";
			blockText  +=  "<label id='"+ itemSeq +"ItemId' class='itemsDetails' style='width:100px; clear:both; display:block;height:20px;'>";
			blockText  +=  "- N.A - </label>";
			blockText  +=  "<label id='"+ itemSeq +"ItemTitle' class='itemsDetails' style='width:510px; display:block;height:20px;'>"
			blockText  +=  	itemTitle ;
			blockText  +=  "</label>";
			blockText  +=  "<label  id='"+ itemSeq +"Status' class='itemsDetails' style='width:70px;text-align=center; display:block;height:20px;'>";
			blockText  +=  "Pending";
			blockText  +=  "</label>";
			blockText  +=  "<label id='"+ itemSeq +"Fees' class='itemsDetails' style='width:50px;text-align=center; display:block;height:20px;'>";
			blockText  +=  "";
			blockText  +=  "</label>";
			blockText  +=  "<label id='"+ itemSeq +"ErrorMessage'>";
			blockText  +=  "<br/>";
			blockText  +=  "</label>";
			blockText  +=  "</Div>";
			
			$('#listings').append(blockText);
		});

	}
	
	
	function BulkListingShowDialog(selectedRows, actionType){
		
					EnableDisableDialogButton('Launch', 1);
					EnableDisableDialogButton('Verify', 1);
					EnableDisableDialogButton('Close', 1);
					$("#loadingImage").css("display","block");
					$("#dialog").dialog (
					{
						buttons: 
						   { 
							   "Close": function(){ 
									$(this).dialog("close");
									if(actionType == "launch"){
										location.href="pending.jsp";
									}else if(actionType == "relist"){
										location.href = "unSold.jsp";
									}
									
								},
							   "Verify": function()
								{ 
										BulkListingsAction(selectedRows, 'verify');
										EnableDisableDialogButton('Verify', 0);
										EnableDisableDialogButton('Close', 0);
										EnableDisableDialogButton('Launch', 0);
								},
							   "Launch": function()
							   { 
										BulkListingsAction(selectedRows, actionType);
										EnableDisableDialogButton('Launch', 0);
										EnableDisableDialogButton('Close', 0);
										EnableDisableDialogButton('Verify', 0);
							   }
						   },
						   width:800,
						   modal: true, 
                           title: "Verify/ Launch - (" + selectedRows.length + ") listings selected.",
						   autoOpen:false,
						   overlay: 
								{ 
									opacity: 0.5, 
									background: "black"
								}  
					});
		if(actionType == "verify"){
			ShowHideDialogButton("Launch",0);	
		}else if(actionType == "launch"){
			ShowHideDialogButton("Launch",1);	
		}else if(actionType == "relist"){
			ShowHideDialogButton("Verify",0);
		}

		$( 'a.ui-dialog-titlebar-close').remove();	
				
	}
	function BulkListingsAction(selectedRows, actionType) {
		var url = "";
		if(actionType == "launch"){
			url = "ListingEditAction.do?postedAction=launchListingAjax"	;
		}else if(actionType == "relist"){
			url = "ListingEditAction.do?postedAction=relistAjax" ;
		}else if(actionType == "verify"){
			url = "ListingEditAction.do?postedAction=verifyListingAjax" ;
		}
		var items = selectedRows;

		for(i=0;i<items.length;i++){		
			if(actionType=="verify"){
				$('#'+ items[i] +'Status').html("Verifying");
			}else{
				$('#'+ items[i] +'Status').html("Launching");
			}

			if(actionType=="launch"){
				var selc = $('input[name=isRemoveFromPendingLaunch]:checked').val();
				if(selc == "true"){
					url += "&isRemoveFromPending=true";
				}else{
					url += "&isRemoveFromPending=false";
				}
			}

			$.getJSON(url +"&listingSeq="+ items[i], function(response){ 					
				BulkListingsResponse(response);
			});
		}
    }
	
	function BulkListingsResponse(data){
		var itemSeq = data.id;
		if(data.errorMessage.length > 0 && data.status == "Failure"){
         	var str = "";
			for(i=0;i<data.errorMessage.length; i++){
				str = str + data.errorMessage[i].errorMessage +"<br/>";	
			}
			$('#'+ itemSeq +'ErrorMessage').html(str);
			$('#'+ itemSeq +'ErrorMessage').addClass('errMessage');
			$('#'+ itemSeq +'ErrorMessage').css('width','720px');
			$('#'+ itemSeq +'Status').html("Failed");
			$('#'+ itemSeq +'Fees').html('-');
			
		}else if(data.errorMessage.length > 0 && data.status == "Verified"){
         	var str = "";
			for(i=0;i<data.errorMessage.length; i++){
				str = str + data.errorMessage[i].errorMessage +"<br/>";	
			}
			$('#'+ itemSeq +'ErrorMessage').removeClass('errMessage');
			$('#'+ itemSeq +'ErrorMessage').css('width','720px');
			$('#'+ itemSeq +'ErrorMessage').addClass('successMessage');
			$('#'+ itemSeq +'ErrorMessage').html(str);
			$('#'+ itemSeq +'Status').html(data.status);
			$('#'+ itemSeq +'Fees').html(data.listingfees)
			
		}else{
			$('#'+ itemSeq +'Fees').html(data.listingfees);
			$('#'+ itemSeq +'Status').html(data.status);
			$('#'+ itemSeq +'ItemId').html(data.itemNumber);			
			$('#'+ itemSeq +'ErrorMessage').html("");
					
		}
		EnableDisableDialogButton('Launch', 0);
		EnableDisableDialogButton('Verify', 0);
		EnableDisableDialogButton('Close', 1);

	}

	
	function ShowHideDialogButton(buttonName,isShow){
		$('.ui-dialog-buttonpane :button').each(
			function()
			{ 
				if($(this).text() == buttonName)
				{
					if(isShow == 1){
						$(this).show();
					}else{
						$(this).hide();
					}
				}
			}
		);
	}
	function EnableDisableDialogButton(buttonName,isEnabled){
		$('.ui-dialog-buttonpane :button').each(
			function()
			{ 
				if($(this).text() == buttonName)
				{
					if(isEnabled == 1){
						$(this).attr('disabled', '');
						$(this).removeClass('ui-state-disabled');
					}else{
						$(this).attr('disabled', 'diabled');
						$(this).addClass('ui-state-disabled');
					}
				}
			}
		);
	}
function createTimeZoneDialog(){
	$('#timeZoneSettings').dialog({
		open:function() {
   			$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
  		},
		autoOpen: false,
		width:500,
		height:300,
		modal: true,
		closeOnEscape:false,
		title: 'Save TimeZone settings',
		buttons: {
			"Close": function() {
				$(this).dialog("close");
			},
			"Save Settings": function() {
				saveTimeZoneSettings();
			}
			
		}
		
	});
	
}
function saveTimeZoneSettings(){
		var formData = $("#settingsForm").serializeArray();
		$.post("SettingsUpdateActionAjax.do?postedAction=updateTimeZoneAjax",formData, function(response){ 					
			ShowHideDialogButton('Close',1);
			$("#savedMessage").html("TimeZone settings saved successfully");
		});
	}
function createHelpDialog(){
	$("#helpDialogDiv").dialog(
			{
				autoOpen: false,
				width: 710,
				height: 500,
                position: ['right','top'],
				modal: true,
				buttons: { 
					"Close": function() { 
						 $(this).dialog("close");
					} 
				},
				title:'Help and Information.',
				modal: true, 
				overlay: { 
					opacity: 0.5, 
					background: "black"
				},
                open: function(event, ui) { 
                    $("#helpContentDiv").html('');
                     var helpID = $("#helpDialogDiv").dialog("option","helpId");
                     $.post("HelpAction.do?action=idSpecificHelpAjax&helpId="+ helpID , function(response){
                        $("#helpContentDiv").html(response);
						$("helpScreenShot.expand").toggler();
                    }); 
                }
	});	
}	

function showHelpDialog(helpId){
    $("#helpDialogDiv").dialog("option","helpId",helpId);
    $("#helpDialogDiv").dialog("open");
}

function showHelpContent(helpID,helpGroupName){
     $("#helpContentText").html("<img src='images/throbber.gif' id='loader' />");
     $("#helpTopicHeader").html(helpGroupName);
     $.post("HelpAction.do?action=idSpecificHelpAjax&helpId="+ helpID , function(response){
        $("#helpContentText").html(response);
		$("helpScreenShot.expand").toggler();
    }); 
}
	
function showHowToContent(howToId,howToHeader){
    $("#helpContentText").html("<img src='images/throbber.gif' id='loader' />");
    $("#helpTopicHeader").html(howToHeader);
    $.post("HelpAction.do?action=idSpecificHowToAjax&howToId="+ howToId , function(response){
        $("#helpContentText").html(response);
		$("helpScreenShot.expand").toggler();
	}); 

}
	

