function ajaxConfirm(url,button){
    $.ajax({
        url: url,
        success: function(data, textStatus){
            if (data > '') alert(data); else confirmSave(button);
        }
    });
}

function ajaxScroll(url,target,button){
	$(target).html('').show().load(url, function(){
		if(button) button.disabled = false;
		$.scrollTo(target, 700);
	});
}

function confirmSave(button){
	if(button) button.disabled = false;
	$.cursorMessage('Update Complete', { offsetX: 20, offsetY: 8 });
}

function ExpandProductList(id, clicked){
    var p = clicked.parentNode.parentNode;
	$("#div_"+id, p).toggle();
	if ($("#img_" + id, p).attr("src") == "/satcms/images/collapse.gif")
	    $("#img_" + id, p).attr("src", "/satcms/images/expand.gif");
	else
	    $("#img_" + id, p).attr("src", "/satcms/images/collapse.gif");
}

function LoadProduct(productID){
    $.ajax({
        url: "/SATCMS/includes/frm_product_view.asp?id=" + productID,
        success: function(data){
            $('#tabareaProducts_View').html(data);
            SelectThisTab('tablinkProducts_View');
            $('#tablinkProducts_NoComm').attr("href", "/SATCMS/includes/Product.asp?id=" + productID);
            $('#tablinkProducts_NoComm').css('display', 'block');
            $('#tablinkProducts_Edit').css('display', 'none');
            url = "/SATCMS/includes/frm_product_edit.asp?id=" + productID;
			$('#tabareaProducts_Edit').load(url, function() {
				PrepProductEdit();
				$('#tablinkProducts_Edit').show();
			});
        } 
    });
}

function PrepProductEdit(){

    $('.ajax').ajaxContent();

    $('#ProductDelete_form').ajaxForm({ 
        beforeSubmit: function(){
            if(confirm('Really delete this product?')==false) return false;
        },
        success: function(){
            $('#tabareaProducts_View').html('');
            $('#tabareaProducts_Edit').html('');
            $('#tablinkProducts_View').hide();
            $('#tablinkProducts_NoComm').hide();
            $('#tablinkProducts_Edit').hide();
            RefreshProductList();
            SelectThisTab('tablinkProducts_Search');
        }
    });

    $('#ProductClone_form, #ProductVariant_form').ajaxForm({ 
        success: function(responseText){
            LoadProduct(responseText);
            RefreshProductList();
        }
    });

    $('#ProductBasic_form').ajaxForm({ 
        success: function(data) {
            $("#ProductNameHeader").html($("#ProductBasic_form #ProductName").val());
            RefreshProductList();
            if (data > '') alert(data); else confirmSave();
        }
    });

    $('#ProductLiquidity_form').ajaxForm({ success: confirmSave });

}

function RefreshProductList(){
	$('#tabareaProducts_Search').html('<b>Reloading... Please wait...</b>');
	$('#tabareaProducts_Search').load("/SATCMS/includes/frm_product_search.asp");
    RefreshProductBrowse();
}

function RefreshProductBrowse(){
    $('#tabareaProducts_Browse').html("<b>Reloading... Please wait...</b>");
	var url = "/SATCMS/includes/frm_product_list.asp?unreleased="+$("#showUnreleasedProducts").is(':checked');
	$('#tabareaProducts_Browse').load(url, function(){ setProductAjax(); });
}

function SaveValue(oButton,sValueID,sTable){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&id=" + sValueID + "&table=" + sTable;
    $("#table_"+sTable+" select,#table_"+sTable+" input").each(function(i){
        if(this.id.substring(this.id.search('~')+1, this.id.length)==sValueID) {
            url += '&'+this.id.substr(0,this.id.search('~'))+'='+encodeURIComponent(this.value);
        }
    });
    url += '&action=SaveTable&sid='+Math.random();
	ajaxConfirm(url, oButton);
}

function AddValue(oButton,sTable){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&table=" + sTable + "&ObjectID=" + objectID;
    $("#table_"+sTable+" select,#table_"+sTable+" input").each(function(i){
        if(this.id.substring(this.id.search('~')+1, this.id.length)==sTable) {
            url += '&'+this.id.substr(0,this.id.search('~'))+'='+encodeURIComponent(this.value);
        }
    });
    url += '&action=AddTable&sid='+Math.random();
	$("#table_"+sTable).load(url);
}

function DeleteValue(oButton,sValueID,sTable){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&id=" + sValueID + "&table=" + sTable;
    url += '&action=DeleteTable&sid='+Math.random();
	$("#table_"+sTable).load(url);
}

function SaveCheckList(oButton, sListType){
    oButton.disabled = true;
    var items = '';
    $("#table_" + sListType + " :checkbox").each(function(i){
        if(this.checked) items += this.id.substr(6)+',';
    });
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + objectID;
    url += '&items='+items.substring(0,items.length - 1);
    url += '&action=SaveCheckList&table='+sListType+'&sid='+Math.random();
    ajaxConfirm(url, oButton);
}

function SelectAllStates(){
    $("#tabareaProductEdit_States :checkbox").attr("checked",true);
}

function UnselectAllStates(){
    $("#tabareaProductEdit_States :checkbox").attr("checked",false);
}

function SaveStates(oButton){
    oButton.disabled = true;
    var states = '';
    $("#tabareaProductEdit_States :checkbox").each(function(i){
        if(this.checked) states += this.id.substr(6)+',';
    });
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + objectID;
    url += '&states='+states.substring(0,states.length - 1);
    url += '&action=SaveStates&sid='+Math.random();
    ajaxConfirm(url, oButton);
}

function EnableField(sFieldID){
    if ($("#"+sFieldID).attr("disabled") == true) {
        $("#"+sFieldID).attr("disabled", false);
    }
    else {
        if (confirm('Do you want to revert back to the base product value?')) {
            $("#"+sFieldID).val($("#"+sFieldID+"__basevalue").html());
            $("#"+sFieldID).attr("disabled", true);
        }
        else {
            return false;
        }
    }
}

function EnableTable(oCheckBox,sProductID,sTable){
    if (oCheckBox.checked) {
        //copy table records from base to variant
        CopyBaseTable(oCheckBox,sProductID,sTable);
    }
    else {
        if (confirm('Do you want to revert back to the base product values?')) {
            //delete table records for variant
            DeleteVariantTable(oCheckBox,sProductID,sTable);
        }
        else {
            return false;
        }
    }
}

function CopyBaseTable(oCheckBox,sProductID,sTable){
    oCheckBox.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID + "&table=" + sTable;
    url += "&action=CopyBaseTable&sid=" + Math.random();
	$("#table_"+sTable).load(url);
}

function DeleteVariantTable(oCheckBox,sProductID,sTable){
    oCheckBox.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID + "&table=" + sTable;
    url += '&action=DeleteVariantTable&sid='+Math.random();
	$("#table_"+sTable).load(url);
}

function EnableStates(oCheckBox,sProductID){
    if (oCheckBox.checked) {
        //copy table records from base to variant
        CopyBaseStates(oCheckBox,sProductID);
    }
    else {
        if (confirm('Do you want to revert back to the base product values?')) {
            //delete table records for variant
            DeleteVariantStates(oCheckBox,sProductID);
        }
        else {
            return false;
        }
    }
}

function CopyBaseStates(oButton,sProductID){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID;
	url += '&action=CopyBaseStates&sid='+Math.random();
	$("#tabareaProductEdit_States").load(url);
}

function DeleteVariantStates(oButton,sProductID){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID + "&states=";
	url += "&action=SaveStates&refresh=y&sid=" + Math.random();
	$("#tabareaProductEdit_States").load(url);
}

function ReleaseProduct(sProductID) {
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID;
    url += "&action=ToggleReleased&sid=" + Math.random();
    ajaxConfirm(url);
}

function ReleaseRider(sRiderID) {
    url = "/SATCMS/includes/ajax_products.asp?object=Rider&RiderID=" + sRiderID;
    url += "&action=ToggleReleased&sid=" + Math.random();
    ajaxConfirm(url);
}

function TopPickProduct(sProductID) {
    url = "/SATCMS/includes/ajax_products.asp?object=Product&ProductID=" + sProductID;
    url += "&action=ToggleTopPick&sid=" + Math.random();
    ajaxConfirm(url);
}

function EditCheckListItem(sItemID,sItemType,sProductID){
    url = "/SATCMS/includes/ajax_products.asp?object=" + sItemType + "&id=" + sItemID + "&ProductID=" + sProductID;
	url += "&action=Edit&sid=" + Math.random();
	ajaxScroll(url,"#div_EditValueList");
}

function EditValueList(sSelect,sValue,sType){
    url = "/SATCMS/includes/ajax_products.asp?object=Value&type=" + sType + "&select=" + sSelect + "&value=" + sValue;
	url += "&action=EditValueList&sid=" + Math.random();
	ajaxScroll(url,"#div_EditValueList");
}

function SaveListChanges(oButton,idValue){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Value&id=" + idValue;
    url += "&short=" + encodeURIComponent($('#short_'+idValue).val());
    url += "&long=" + encodeURIComponent($('#long_'+idValue).val());
    if($('#extra_'+idValue)[0]) url += "&extra=" + encodeURIComponent($('#extra_'+idValue).val());
    if($('#category_' + idValue)[0]) url += "&category=" + encodeURIComponent($('#category_'+idValue).val());
    url += "&action=SaveValue&sid=" + Math.random();
    $.ajax({
        url: url,
		beforeSend: function(xhr) {
			xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
		},
        success: function(){
	        confirmSave(oButton);
	    }
    });
}

function AddListValue(oButton,idType){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Value&id=" + idType;
    url += "&short=" + encodeURIComponent($('#short_'+idType).val());
    url += "&long=" + encodeURIComponent($('#long_'+idType).val());
    if($('#extra_'+idType)[0]) url += "&extra=" + encodeURIComponent($('#extra_'+idType).val());
    url += "&action=AddValue&sid=" + Math.random();
    $.ajax({
        url: url,
		beforeSend: function(xhr) {
			xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
		},
        success: function(data, textStatus){
   	        $("#div_"+idType).html(data);
        }
    });
}

function DeleteListValue(oButton,idValue,idType){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Value&id=" + idValue;
    url += "&action=DeleteValue&sid=" + Math.random();
	$("#div_"+idType).load(url);
}

function MoveListValue(oButton,idValue,idType,iMove){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Value&id=" + idValue;
    url += "&action=MoveValue&move=" + iMove + "&sid=" + Math.random();
	$("#div_"+idType).load(url);
}

function RefreshSelect(sSelect,sValue){
    url = "/SATCMS/includes/ajax_products.asp?object=Value&select=" + sSelect + "&value=" + sValue;
	url += "&action=RefreshSelect&sid=" + Math.random();
	var $parent = $("#tabareaProducts_Edit #"+sSelect.replace('~','\\~')).parent();
	$parent.load(url, ClearValueListEdit);
}

function ClearValueListEdit(){
	$('#div_EditValueList').hide();
	$('#div_EditValueList').html('');
}

function MarkCurrent(sField,sInsCompanyID){
    url = "/SATCMS/includes/ajax_products.asp?object=Product&company=" + sInsCompanyID;
    url += "&action=Mark"+sField+"Current&sid=" + Math.random();
	$("#"+sField+"Date_"+sInsCompanyID).load(url);
}

function SearchProductsBasic(oButton) {
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&action=SearchProductsBasic";
    $("#BasicProductSearchFields select,#BasicProductSearchFields input,#BasicProductSearchFields textarea").each(function(i) {
        if (this.id.search('__') == -1 && this.value > '' && $('#' + this.id.replace('~', '\\~').replace('!', '\\!') + '__operator')[0]) {
            url += '&' + this.id + '=' + encodeURIComponent($('#' + this.id.replace('~', '\\~').replace('!', '\\!') + '__operator').val() + '_' + this.value);
        }
    });
	if ($('#showUnreleasedProducts').is(':checked')) url += '&unreleased=true';
    var states = '';
    $("#tabareaProductBasicSearch_States :checkbox").each(function(i) {
        if (this.checked) states += this.id.substr(6) + ',';
    });
    url += '&states=' + states.substring(0, states.length - 1);
    url += '&sid=' + Math.random();
	ajaxScroll(url, "#BasicProductSearchResults", oButton);
}

function SearchProducts(oButton){
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Product&action=SearchProducts";
    $("#ProductSearchFields select,#ProductSearchFields input,#ProductSearchFields textarea").each(function(i){
        if(this.id.search('__') == -1 && this.value > '' && $('#'+this.id.replace('~','\\~')+'__operator')[0]){
            url += '&'+this.id+'='+encodeURIComponent($('#'+this.id.replace('~','\\~')+'__operator').val()+'_'+this.value);
        }
    });
	if ($('#showUnreleasedProducts').is(':checked')) url += '&unreleased=true';
    var states = '';
    $("#tabareaProductSearch_States :checkbox").each(function(i){
        if(this.checked) states += this.id.substr(6)+',';
    });
    url += '&states='+states.substring(0,states.length - 1);
    url += '&sid='+Math.random();
	ajaxScroll(url, "#ProductSearchResults", oButton);
}

function SearchRiders(oButton) {
    oButton.disabled = true;
    url = "/SATCMS/includes/ajax_products.asp?object=Rider&action=Search";
    $("#RiderSearchFields select,#RiderSearchFields input").each(function(i) {
        if (this.id.search('__') == -1 && this.value > '' && $('#' + this.id.replace('~', '\\~').replace('!', '\\!') + '__operator')[0]) {
            url += '&' + this.id + '=' + encodeURIComponent($('#' + this.id.replace('~', '\\~').replace('!', '\\!') + '__operator').val() + '_' + this.value);
        }
    });
	if ($('#showUnreleasedProducts').is(':checked')) url += '&unreleased=true';
    url += '&sid=' + Math.random();
	ajaxScroll(url, "#RiderSearchResults", oButton);
}

function onLoad_Rider(){

	if ($("#rider_form").length==1) {

		$("#rider_form").validationAideEnable(null, { showInlineMessages: true, summaryElementId: 'RiderValidation' });
		
		$("#rider_form").ajaxForm({
			beforeSubmit:  function(formData, jqForm, options) { 
				if($('input[name=Action]').fieldValue()[0]=='Delete') {
					if(confirm('Really delete this rider?')==false) return false;
				}
				if($('#RiderValidation').html()=='') return true; else return false;
			},
			success:  function(responseText) {
				confirmSave();
				if(responseText=="Deleted") {
					$('#tabareaProducts_View').html('');
					$('#tabareaProducts_Edit').html('');
					$('#tablinkProducts_View').hide();
					$('#tablinkProducts_NoComm').hide();
					$('#tablinkProducts_Edit').hide();
					SelectThisTab('tablinkProducts_RiderSearch');
					$.scrollTo("body", 700);
				}
				else if(responseText.length==36){
					$('#tabareaProducts_Edit').load("/SATCMS/includes/frm_rider_edit.asp?id="+responseText);
					$.scrollTo('#tabareaProducts_Edit', 700);
				}
				else if(responseText>''){
					$("#table_2Rider").html(responseText);
					ClearValueListEdit();
					$.scrollTo("#table_2Rider", 700);
				}
				else {
				}
			}
		});
		
		$("#rider_form textarea").autoResize({ extraSpace: 12 });
		
		$('#riderCost_form').ajaxForm({ success: confirmSave });

		$('#riderIncome_form').ajaxForm({ success: confirmSave });

		$("#riderProduct_form").ajaxForm({ success: confirmSave });
		
		$("#riderMerge_form").ajaxForm({
			success:  function() {
				confirmSave();
				$('#CompanyRiders > div').has(':checked').fadeOut('slow',function(){$(this).remove()});
			}
		});

	}
}
