function updateImprintColorEvents(){
    $('.imprint_color_entry').css('cursor', 'pointer').click(ImprintColorClickEvent);
    $('.imprint_color_entry input').attr('readonly', 'true').css('cursor', 'pointer').click(function(e){$(this).parent().click();return false;});
    $('.imprint_color_entry input').each(function(){
        var text = 'Select a Color';
        if(client_code == 'rush_canada') {
            text = 'Select a Colour';
        }
    	if($(this).val() == '') $(this).val(text);
    });
    $('.imprint_method_box select').change(imprintColorCountChanged);
    $('#productionTimeID').change(update_qty_event);
}

function imprintColorCountChanged() {
    element = $('.imprint_method_box select')[0];
    if(!element) {
        return;
    }
//    if(element.options[element.selectedIndex].text == 'Deboss') {
    if(element.options[element.selectedIndex].text == 'Deboss'
        || element.options[element.selectedIndex].text == 'Laser Engrave') {
        $('#num_imprint_colors').val(0);
        updateImprintColorPricing();
        $('.imprint_colors_count_box').hide();
        $('.imprint_colors_box').hide();
    } else {
        if($('#num_imprint_colors').val() == 0) {
            $('#num_imprint_colors').val(1);
        }
        updateImprintColorPricing();
        $('.imprint_colors_count_box').show();
        $('.imprint_colors_box').show();
    }
}
function setImprintColorMsg(msg){
    if(msg == '') $('#imprint_colors_msg').html('').hide();
    else $('#imprint_colors_msg').html(msg).show();
}

function setImprintColorCount(formQty, colorCount, colorToolTip){
    if(formQty != $('#product_quantity').val()) return; // nope, guess not!

    // I know how many colors should be coming in, now I just need to check how
    // many there were before and update that if needed.

    // First, set the color tip.
    setImprintColorMsg(colorToolTip);
    //$('#imprint_colors_msg').html(colorToolTip);

    // The amount of colors currently.
    var colorsCurrent = $('#num_imprint_colors').children('option').length-1;

    // If the color counts match, GREAT... nothing to do!
    if(colorsCurrent == colorCount) return;

    // remove all options
    while($('#num_imprint_colors').children('option').length > 0) {
        $($('#num_imprint_colors').children('option')[0]).remove();
    }
    // add new options
    for(i=1; i<=colorCount; i++){
        $('#num_imprint_colors').append(
            '<option value="' + i + '">' + i + '</option>'
        );
    }
    $('#num_imprint_colors').append('<option value="0" class="hidden_zero_imprint_color">0</option>');
    
    updateImprintColorPricing();
    
    return;
}

function updateColorSelectEvents(){
    $('.ColorSelect').click(function(){
        $(lastColorOptionClicked).children('input').val($(this).attr('attr:name'));
        $(lastColorOptionClicked).children('input').attr('attr:code', $(this).children('.colorSwatch').css('backgroundColor'));
        $(lastColorOptionClicked).children('.colorSwatch').css('backgroundColor', $(this).children('.colorSwatch').css('backgroundColor'));
        $(lastColorOptionClicked).children('.colorSwatch').show();
        $(lastColorOptionClicked).children('.colorSwatchMask').show();
        
        $('#ColorSelection').dialog('close').css('z-index', '-1');
        //alert(typeof($('#popup_email').find('#popup_email_address')));
        /*
        if (typeof($('#popup_email').find('#popup_email_address'))!='untitled'){
        	$('#popup_email').find('#popup_email_address').focus();
        }
        */
    });
}

function ImprintColorClickEvent(e){
    var target = e.target;
    var event = 'na';

    if(e.clientX == undefined){
        // User clicked inside the input box.
        event = 'color';
    }
    else{
        if(e.clientX - $(target).offset().left < 135) event = 'color';
        else event = 'pms';
    }

    lastColorOptionClicked = target;

    $('#ColorSelection')
    .dialog({
        autoOpen: true,
        height: 400,
        width: 600,
        resizable: false,
        zIndex: 1100,
        close: function () {$(this).dialog('destroy').css('z-index', '-1');}
    });

    $('#ColorSelection').dialog('open').dialog('moveToTop');
    if(event == 'color') $('#ColorSelection').tabs('select', 0);
    else $('#ColorSelection').tabs('select', 1);
}

// This is needed to check the last submitted query.
var gVal;

// This is needed to remember which input box the user clicked on.
var lastColorOptionClicked;

function pantoneSearch(e){
    // Do nothing if the user only typed 1 character.
    if(e.target.value.length < 2) return;


    var val = e.target.value;
    // If the new value is the same as gVal, no change, so no need to recheck.
    if(val == gVal) return;
    gVal = val;

    $('#pantoneSearchResults').html('searching...').fadeIn();
    $.ajax({
        url: 'ajax_handler.php',
        dataType: 'json',
        data: {
            page: 'avp_pantone_search',
            q: val,
            output: 'json'
        },
        async: false,
        success: function(r){
            if(gVal != val) return;
            resultEl = $('#pantoneSearchResults');
            resultEl.html(''); // Blank out the result pane.

            for(i in r.results){
                if(typeof(r.results[i]) == 'function') continue;
                resultEl.append('<div attr:name="PMS: ' + r.results[i].name + '" class="ColorSelect" title="' + r.results[i].name + '"><div class="colorSwatch" style="background:' + r.results[i].hex_value + ';"></div><span class="colorSwatchMask">&nbsp;</span>&nbsp;PMS: ' + r.results[i].name + '</div>');
            }
            if(resultEl.html() == '') resultEl.html('No match found.<div attr:name="PMS: ' + r.query + '" class="ColorSelect">Add PMS: ' + r.query + ' anyway</div>');
            else resultEl.append('<br clear="left"/>');

            updateColorSelectEvents();
        }
    });

    return;
};


function updateImprintColorPricing()
{
    // get pricing and number of colors
    // Now handled by the global JS variable, ImprintPricePerColor

    var temp             = document.getElementById('num_imprint_colors');
    if(typeof(temp) == 'undefined' || temp == null) return; // Guess there are no colors... np then.
    if(temp.type == 'hidden') var numImprintColors = temp.value;
    else var numImprintColors = temp.options[temp.selectedIndex].value;

    // update the value
    var price = document.getElementById('imprint_color_charge');
    price.innerHTML = '(+ $'+ formatMoney((numImprintColors-1) * ImprintPricePerColor) +' run charge)';

    // get the old values, if any
    var colors = new Array();
    for (var ii=1; ii<=numImprintColors; ii++)
    {
        colors[ii] = document.getElementById('imprint_colors_'+ii);
    }

    // update the color name input boxes
    if(document.getElementById('color_names') != null){
            var nameBoxes = document.getElementById('color_names');
            nameBoxes.innerHTML = '';
            for (var ii=1; ii<=numImprintColors; ii++)
            {
                var colorName = '';
                var style1 = 'display: none;';
                var style2 = 'display: none;';
                var colorCode = '';
                if (colors[ii] && colors[ii] != 'undefined') {
                    colorName = colors[ii].value;
                    colorCode = $(colors[ii]).attr('attr:code');
                    if(colorCode && colorCode != 'undefined') {
                        style1 = 'background-color: ' + colorCode;
                        style2 = '';
                    }
                }

                nameBoxes.innerHTML += '<div class="imprint_color_entry">' +
                    '<div style="' + style1 + '" class="colorSwatch"></div>' +
                    '<span class="colorSwatchMask" style="' + style2 + '">&nbsp;</span>' +
                    '<input type="text" value="'+ colorName +'" name="id[imprint_colors_10][]" id="imprint_colors_' + ii + '" attr:code="' + colorCode + '"/>' +
                '</div>';
            }
        updateImprintColorEvents();
    }

}


/**
 * Karn - check imprint color
 *
 * make sure that if the customer selects 4 colors, all 4 boxes are filled out
 * also trim the white spaces around the text
 */
function checkImprintColors()
{
    var result           = true;
    var temp             = document.getElementById('num_imprint_colors');

    // if there's no imprint color, return true
    if (document.getElementById('num_imprint_colors') != undefined) {temp = document.getElementById('num_imprint_colors');}
    else if (document.getElementById('numColors') != undefined) {temp = document.getElementById('numColors');}
    else return true;

    if(temp.type == 'hidden') return true;

    var text = 'Select a Color';
    var text2 = 'Please fill out all the imprint colors, or select a different number of colors.';
    if(client_code == 'rush_canada') {
        text = 'Select a Colour';
        text2 = 'Please fill out all the imprint colours, or select a different number of colours.';
    }
    
    var numImprintColors = temp.options[temp.selectedIndex].value;
    for (var ii=1; ii<=numImprintColors; ii++)
    {
        var color = document.getElementById('imprint_colors_'+ii);
        if (trim(color.value) == '' || color.value == text)
        {
            alert(text2);
            result = false;
            break;
        }
    }

    return result;
}

function checkLogo(){
    var els = $("input[name='id[logo_7]']");
    if(els.length == 1 && els.attr('required') && (els.val() == '' || els.val() < 0)){
        alert('Please select a logo.');
        return false;
    }
    else if(els.length > 1){
        var required = false;
        var logoPresent = false;
        els.each(function(){
            if($(this).attr('required')) required = true;
            if($(this).attr('checked')) logoPresent = true;
        });
        if(required && ! logoPresent){
            alert('Please select a logo.');
            return false;
        }
    }
    return true;
}

function check_product_min_quantity()
{

  var result = true;
  // product_min_quantity can now be accessed from the global ProductMinQty variable.
  var quantity = document.getElementById('product_quantity').value;
  var el = $('#ProductionTime-' + $('#productionTimeID').val());
  if(el.length > 0){
      if(quantity < parseInt(el.attr('min_qty'))){
          alert('The minimum quantity required for the selected production time is '+ el.attr('min_qty') +'.');
          return false;
      }
  }
  else if(quantity < ProductMinQty){
    alert('The minimum quantity required for this product is '+ ProductMinQty +'.');
    return false;
  }
  else if(quantity <= 0){
      alert('Please enter a quantity more then 0.');
      return false;
  }

  // check bulk mailing quantity
  var bulk_mailing = document.getElementById('txt_16');
  if (result && bulk_mailing) {
      if (parseInt(bulk_mailing.value) > quantity) {
          alert('Bulk mailing quantity has to be less than or equal to \nthe quantity you have chosen before ('+ quantity +' items)!');
          return false;
      }
  }


    // Also check any required field on the form.
    //console.log($('#cart_quantity'));
    form = $('#cart_quantity')[0];

    //console.log(this.elements);
    for(x=0; x<form.elements.length; x++){
        //console.log(form.elements[x]);

        if(form.elements[x].tagName != 'INPUT') continue; // Only parse input type elements.

        obj = $(form.elements[x]);
        //console.log(obj);
        if(!obj.attr('required')) continue; // This element doesn't have the required flag.
        if(obj.val() == ''){
            alert('Please ensure that you filled in all required form information.');
            //console.log('That element failed the check.');
            return false;
        }
    }

  return result;
}

function hide_add_to_cart(event) {
    //if we're updating price because num imprint colors or incremental quantities via a select field, we don't care about the key press
    if (event && event.type=="change") {
        $('#totalPriceValue').html('updating...');
        $('#totalPriceValue_copy').html('updating...');
        $('#add_to_submit_div').hide();
    	$('#updating_price_message_div').show();
    }
    //otherwise the function should only do work if the key pressed was a number
    else {
        if (isNumber(event)) {
            $('#totalPriceValue').html('updating...');
            $('#totalPriceValue_copy').html('updating...');
            $('#add_to_submit_div').hide();
	        $('#updating_price_message_div').show();
            return true;
        }
            return false;
    }
}

function getProductionEstimate(intDaysValue, strFormat, JQObjectToUpdate){
    JQObjectToUpdate.html("loading...");
    $.ajax({
        url: 'ajax_handler.php?page=get_production_date&days=' + intDaysValue + '&format=' + strFormat,
        success: function(data, textStatus){
            JQObjectToUpdate.html(data);
        }
    });
}

//make sure the customer has selected a color
function check_product_color(){

    // There are no colors for this product, thus the check just needs to continue.
    if(!ProductHasColors) return true;

    // if this product has color, check for a selection
    var els = $('[name="id[color_6]"]');

    if(els.length == 1 && els.is('select')){
        return true;
    }
    else if ($('[name="id[color_6]"]').attr("type")=="hidden"){
    	if (Number($('[name="id[color_6]"]').val()) > 0) return true;
    }
    else{
        var result = false;
        $('[name="id[color_6]"]').each(function(){
            if($(this).attr('checked')) result = true;
        });
        if(result) return true;
    }

    // if it's gotten here, all of the above checks failed.
    var text = 'Please select a color.';
    if(client_code == 'rush_canada') {
        text = 'Please select a colour.';
    }
    alert(text);
    return false;
}

function submitFormChecks(){
    // Run any pre-submit checks here.  Return true if successful, false else.
    var quickClick = (document.press == "Add n' Stay");
    var result = true;

    if(!(checkImprintColors())){
        result = false;
    } else if(typeof(checkLogo) == 'function' && !(checkLogo())){
        result = false;
    } else if(!(check_product_min_quantity())){
        result = false;
    } else if(!(check_product_color())){
        result = false;
    } else if(!(checkCustomFields())){
        result = false;
    }

    if(($('#dialog_quick_view').length > 0 || quickClick) && (result)) {
        result = submit_quick_view_form(quickClick);
    }

    return result;
}


function submit_quick_view_form(quickClick) {
    var product_id = $('input[name="products_id"]').val();
    var orderCount = $('#quickClickOrders').text().match(/[\d]+$/);
    var origTextColor = $('#totalPriceValue').css('color');

    $.ajax({
        url: "shopping_cart.php?action=add_product&no_redirect=true",
        type: "POST",
        data: $('#cart_quantity').serialize(),
        dataType: 'json',
        success: function(data){
            $('.inYourCartDiv_' + product_id).show();
            $('.badge-icon_' + product_id).hide();
            $('.quick_view_link img.checkbox_product_' + product_id).attr('src', 'templates/massage_envy/site_images/selected.png');
            $('.quick_view_link img.checkbox_product_' + product_id).attr('alt', 'In Cart');
            $('.ShoppingCartBox').load('ajax_handler.php?page=get_box&box=shopping_cart', function() {
                $('.ShoppingCartBox').replaceWith($('.ShoppingCartBox').html());
            });
            

            var message = 'Number of times this product has been added to your cart: ';
            var products = 0;
            var quantities = 0;
            for(var i = 0; i<data.length; i++) {
                if(parseInt(data[i].id) == parseInt($('input[name="products_id"]').val())) {
                    products++;
                    quantities += parseInt(data[i].quantity);
                }
            }
            $('#quickClickOrders').text(message + products);
            $('#quickClickOrders')
                .animate({"backgroundColor":"yellow", "color":"red"}, 2000)
                .animate({"backgroundColor":"transparent","color":origTextColor}, "fast");
        }
    });

    if (!quickClick) {
        $("#dialog_quick_view").dialog("close");
    }

    return false;
}

/**
 * The function that is called whenever the quantity is updated.
 *
 * Should fire off requested to get the newest price from the server.
 */
function update_qty_event(o){
//alert(isNumber(o.value));
    xajax_update_price(xajax.getFormValues('cart_quantity'));
    xajax_update_imprint_colors(xajax.getFormValues('cart_quantity'));
}

/**
 * The function that is fired off when the data is returned from the server
 *  when requesting the price.  If the quantity doesn't match up, the request
 *  will be ignored.
 */
function update_qty_returned(requestedQty, newValue){
    if(requestedQty != $('#product_quantity').val()) return; // nope, guess not!

    $('#totalPriceValue').html(newValue);
    $('#totalPriceValue_copy').html(newValue);
    $("#add_to_submit_div").show();
    $("#updating_price_message_div").hide();
}

$(function(){
    imprintColorCountChanged();
    
    updateImprintColorEvents();

    updateColorSelectEvents();

    setImprintColorMsg('');

    $('#pantoneSearch').keyup(pantoneSearch).click(pantoneSearch);
    $('#ColorSelection')
    .tabs()
    .dialog({
        modal: true,
        autoOpen: false,
        height: 400,
        width: 600,
        resizable: false,
        close: function () {$(this).dialog('destroy').css('z-index', '-1');}
    });

    $(".box-center-productInfo").show();
    xajax_update_price(xajax.getFormValues('cart_quantity'));

    // Disable lytebox's autoresize feature.  Tends to make product images appear too small.
    if(typeof(myLytebox) == 'object') myLytebox.autoResize = false;

    $("#badge_icons").show();
});

function start_loading_dialog_nice() {
	$('<div id="loading_dialog" style="text-align:center;"><img src="templates/default/site_images/ajax_loader.gif"/ ></div>').dialog({
		modal: true,
		title: "Please Wait",
		resizable:false,
		draggable:false,
		close: function () {
			$(this).dialog("destroy").remove();
		}
	}).siblings(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").remove();
}

/* close the loading dialog */
function close_loading_dialog_nice() {
	$("#loading_dialog").dialog("close");
}

/* it checks for fields which are depends on the values of other fields
 * i.e. MM# for FL state only in massage envy client.
 * It enables only those fields which have to be filled for selected state
 *
 * Now works for states only.
 * */
$().ready(function() {
	$('select').each(function() {
		proccess_custom_field_dependecies(this);
	});
});
function proccess_custom_field_dependecies(element) {
	if(element.nodeName == 'SELECT') {
		var state_regex = new RegExp('state','i');
		if(state_regex.test(element.id)) {
			var inputs = $('input');
			var dep_all_regex = new RegExp('[a-z]{2}_only','i');
			inputs.each(function(){
				if(dep_all_regex.test(this.id)) {
					this.disabled = false;
				}
			});
			for(var i = 0; i<element.options.length; i++) {
				if(element.options[i].value == '') continue;

				dep_regex = new RegExp(element.options[i].value + '_only','i');
				if(!element.options[i].selected) {
					inputs.each(function(){
						if(dep_regex.test(this.id)) {
							this.disabled = true;
						}
					});
				}
			}
		}
	}
}

function custom_field_autocomplete(changed_element) {
    var auto_complete_fields = $("body").data("auto_complete_fields") || new Array();

    $.ajax({
        url: "ajax_handler.php?page=custom_fields_autocomplete",
        data: 'changed_field=' + changed_element.name + '&' + $('#cart_quantity').serialize(),
        dataType: 'json',
        type: "POST",
        success: function(Data) {

            // change autocomplete fields ui back to normal in case selected store does not have autocomplete set
            var pattern = new RegExp("^(\\d+\\*clinic_[a-z]_name\\*[required]*)$", "i");
            var pattern_pricepoint = new RegExp("(intro)|(price)", "i");
            var pattern_keytag = new RegExp("^\\d+\\*bar_code_number\\*required","i");

            var match = changed_element.name.match(pattern);

            // make sure changed field is clinic name
            if (match) {
                if (auto_complete_fields.length) {
                    for (var i = 0; i < auto_complete_fields.length; i++) {
                        var fld_name = auto_complete_fields[i];
                        if (fld_name.match(pattern_pricepoint) || fld_name.match(pattern_keytag)) {

                            $("input[name=" + auto_complete_fields[i] + "]")
                                .removeAttr("readonly")
                                .removeClass("auto-complete-field")
                                .val("");
                        }
                    }
                    auto_complete_fields = new Array();
                }

                for(var i = 0; i < Data.length; i++) {
                    var fld_name = Data[i].name;
                    var input = $("input[name=" + fld_name + "]");

                    auto_complete_fields.push(fld_name);

                    if (input.length > 0) {
                        input.val(Data[i].value);

                        // make designated fields uneditable (i.e. Price Points, Key tags bar codes)
                        if (Data[i].read_only) {
                            input
                                .attr("readonly", "readonly")
                                .addClass("auto-complete-field");
                        }
                    }
                }
                $("body").data("auto_complete_fields", auto_complete_fields);
                
            }
        }
    });
}

function save_linked_custom_field() {
    $.ajax({
        url: "ajax_handler.php?page=custom_fields_autocomplete&other_params[save_linked_custom_fields]=true",
        data: $('#cart_quantity').serialize(),
        dataType: 'json',
        type: "POST"
    });
}

var globCount = 0;
var aRegFildsChange = new Array();

function selectBox (iCount)
{
    //alert(iCount);
	if (globCount < iCount)
	{
		for(var i = 1; i <= iCount; ++i)
		{
			sNameOfElem ="tr[name=element_"+i+"] ";
			elemJ = $(sNameOfElem);
			elemJ.css('display','');

			for(var ii=0; ii<elemJ.length; ii++)
			{
				var index = elemJ[ii].getAttribute('index');

				if (aRegFildsChange[index] != 'undefined')
				{
					if (customFields[index].isRequiredForJs)
					{
						customFields[index].required = 1;
					}
				}
			}
		}

		aRegFildsChange = new Array();
	}
	else
	{
		for(var i = globCount; i > iCount; i--)
		{
			sNameOfElem ="tr[name=element_"+i+"] ";
			elemJ = $(sNameOfElem);
			elemJ.css('display','none');

			for(var ii=0; ii<elemJ.length; ii++)
			{
				var index = elemJ[ii].getAttribute('index');

				if (customFields[index].required)
				{
					customFields[index].required = 0;
					aRegFildsChange[index] = 1;
				}

				elemInput = $('#'+index+'_'+customFields[index].fieldKey);
				elemInput.val(' ');
			}

		}
	}

	globCount = iCount;
}

$().ready(function() {
    // add click event function for 'request free sample' button
    $('#request_free_sample_button').click(function() {
        var product_id = $('#cart_quantity > input[name="products_id"]').val();
        var color_id = $('#cart_quantity > input[name="id[color_6]"]').val();

        window.location = 'free_sample_request.php?product_id=' + product_id + '&color_id=' + color_id;

        return false;
    });

    // assign event handler to custom fields for autocompletion
    $('.custom_fields input').change(function() {
        custom_field_autocomplete(this);
    });
    $('.custom_fields select').change(function() {
        custom_field_autocomplete(this);
    });

    $('#btnAddToCart').live('click', save_linked_custom_field);
});

function createCampaignformSubmit() {
    $('#campaign_error_messages').html('');
    if ( $("#create_campaign_form").valid() == true ) {

        sData  = $("#create_campaign_form").serialize();

        $.ajax({
                url:  'ajax_handler.php',
                type: "POST",
                dataType: 'json',
                data: sData,
                success:function (Data) {
                    if (Data.status == 'success') {
                        $('#campaignEditDialog').dialog("close");
                        return true;
                    } else {
                        for(i=0; i < Data.errors.length; i++ ) {
                          $('#campaign_error_messages').html( Data.errors[i] );
                        }
                    }
                },
                close :function () {
                    $('#campaignEditDialog').dialog("destroy");
                }
            });
            return true;
    }

    return false;
}

function getCampaignInformation(iCampaignId,sCampaignName)
{
    if($('#campaignEditDialog').length == 0) {
        $('body').append('<div id="campaignEditDialog"></div>');
    }

    $("#campaignEditDialog").dialog({
        title: 'Edit '+sCampaignName+' Campaign',
        width: 650,
        resizable:false,
        modal:true,
        open:function(){
            $('#campaignEditDialog').html("Loading...")
            sData = 'page=product_campaign_info&cid='+iCampaignId;
            $.ajax({
                    url:  'ajax_handler.php',
                    type: "POST",
                    dataType: "html",
                    data: sData,
                    success:function (Data) {
                        $('#campaignEditDialog').html(Data);
                    }
                });
        },
        close: function() {
            iProductId = $("input:[name='products_id']").val();
            sData = 'action=campaign_list&page=product_campaign_actions&cid='+iCampaignId+'&pid='+iProductId;
            $.ajax({
                url:  'ajax_handler.php',
                type: "POST",
                dataType: "json",
                data: sData,
                async:false,
                success:function (oData) {

                    if(oData.status == 'success'){
                        $('#campaignList').html(oData.sCampaignListHTML);
                    }

                }
            });

            $('#campaignEditDialog').dialog("destroy");
        },
        buttons: {
            "Close": function() {
                $('#campaignEditDialog').dialog("close");
            },
            "Save Changes": function() {
                sData  = $("#editCampaignForm").serialize();
                $.ajax({
                    url:  'ajax_handler.php',
                    type: "POST",
                    dataType: "json",
                    data: sData,
                    async:false,
                    success:function (oData) {
                        if(oData.status == 'success'){
                            $('#campaignEditDialog').dialog("close");
                        }
                    }
                });

                $('#campaignEditDialog').dialog("destroy");
            }
        }
    });
}

function deleteCampaign(iCampaignId,iProductId)
{
    if (confirm("Do you want to delete this campaign ?")) {
        sData = 'action=delete_campaign&page=product_campaign_actions&cid='+iCampaignId+'&pid='+iProductId;
        $.ajax({
            url:  'ajax_handler.php',
            type: "POST",
            dataType: "json",
            data: sData,
            success:function (oData) {

                if(oData.status == 'success'){
                    $('#campaignList').html(oData.sCampaignListHTML);
                }

            }
        });
        return true;
    }

    return false;
}

function removeCampaignProduct(iProductId,iCampaign)
{
    if (confirm("Do you want to delete this product from this campaign?")) {
        sData = "page=product_campaign_actions&action=deleteproduct&cid="+iCampaign+"&pid="+iProductId;

        $.ajax({
            url:  'ajax_handler.php',
            type: "POST",
            dataType: "json",
            data: sData,
            success:function (oData) {

                if(oData.status == 'success'){
                    var sHtml = '';
                    if (oData.products.length) {
                        sHtml = '<ul>';
                        $.each(oData.products, function(i,item){
                            sHtml += '<li><a href="'+item.product_link+'">'+item.product_name+'</a>';
                            sHtml += ' <img src="templates/default/icons/actions/delete-14x14.png" align="absmiddle" onclick"=return removeCampaignProduct('+item.product_id+','+item.campaign_id+')>';
                            sHtml += '</li>';
                        });

                        sHtml += '</ul>';
                    } else {
                        sHtml = "You don't have any products in this campaign.";
                    }


                    $('#campaignProductList').html(sHtml);
                }

            }
        });

        return true;
    }
    return false;
}

