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(){
    	if($(this).val() == '') $(this).val('Click Here');
    });
    //Click Here
}

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;
    
    // If the color counts match, GREAT... nothing to do!
    if(colorsCurrent == colorCount) return;
    
    // If not enough, add some!
    if(colorsCurrent < colorCount){
        for(i=colorsCurrent+1; i<=colorCount; i++){
            //console.log(i);
            //console.log(colorCount);
            //$('#color_names').append(
            //    '<div class="imprint_color_entry" style="cursor: pointer;">' + 
            //    '<input type="text" id="imprint_colors_' + i + '" name="id[imprint_colors_10][]" value=""/>' +
            //    '</div>'
            //);
            $('#num_imprint_colors').append(
                '<option value="' + i + '">' + i + '</option>'
            );
        }
        updateImprintColorEvents();
        return;
    }
    
    // Too many?  alright, we can handle that too...
    if(colorsCurrent > colorCount){
        // Set the drop down to the biggest value.
        if($('#num_imprint_colors').val() > colorCount) $('#num_imprint_colors').val(colorCount);
        
        // I don't want too many color inputs.
        while($('#color_names').children('.imprint_color_entry').length > colorCount){
            $($('#color_names').children('.imprint_color_entry')[$('#color_names').children('.imprint_color_entry').length-1]).remove();
        }
        
        for(i=colorsCurrent; i>colorCount; i--){
            
            //$($('#color_names').children('.imprint_color_entry')[i-1]).remove();
            
            $($('#num_imprint_colors').children('option')[i-1]).remove();
        }
        updateImprintColorPricing();
        return;
    }
}

function updateColorSelectEvents(){
    $('.ColorSelect').click(function(){
        $(lastColorOptionClicked).children('input').val($(this).attr('attr:name'));
        $('#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 < 194) event = 'color';
        else event = 'pms';
    }

    lastColorOptionClicked = target;

    $('#ColorSelection')
    .dialog({
        modal: true,
        autoOpen: true,
        height: 400,
        width: 600,
        resizable: false,
        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>&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 = '';
                if (colors[ii] != null) {colorName = colors[ii].value;}

                nameBoxes.innerHTML += '<div class="imprint_color_entry"><input type="text" value="'+ colorName +'" name="id[imprint_colors_10][]" id="imprint_colors_' + ii + '"/></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 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 == 'Click Here')
        {
            alert('Please fill out all the imprint colors, or select a different number of colors.');
            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) {
    $('#totalPriceValue').html('updating...');
    //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.type=="change") {
    	$('#add_to_submit_div').hide();
    	$('#updating_price_message_div').show();
        //document.getElementById('add_to_submit_div').style.display='none';
        //document.getElementById('updating_price_message_div').style.display='inline';
    }
    //otherwise the function should only do work if the key pressed was a number
    else {
        if (isNumber(event)) {
	        $('#add_to_submit_div').hide();
	        $('#updating_price_message_div').show();
	        //document.getElementById('add_to_submit_div').style.display='none';
	        //document.getElementById('updating_price_message_div').style.display='inline';
            return true;
        }
        else 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.
    alert("Please select a color.");
    return false;
}

function submitFormChecks(){
    // Run any pre-submit checks here.  Return true if successful, false else.
    if(!(checkImprintColors())){
        return false;
    }

    if(typeof(checkLogo) == 'function' && !(checkLogo())){
        return false;
    }
    
    if(!(check_product_min_quantity())){
        return false;
    }
    if(!(check_product_color())){
        return false;
    }
    if(!(checkCustomFields())){
        return false;
    }
    return true;
}

/**
 * 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(){
    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);
    $("#add_to_submit_div").show();
    $("#updating_price_message_div").hide();
}

$(function(){
    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;
});

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");
}