
/*
* Selected item handler.
*/

function afterLoadProduct() {
    // set focus to amount field
	if (document.getElementById('product_price') != null) {
		if ($("div.box ul.prices li").html().length > 0) {
			// set focus to amount field
			$("a.add-to-order-submit input").select();
		}
	} else {
		$("input#searchbox").select();
	};
    imgScale();
}


// http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
$(window).load(function() {
    imgScale();
});

function imgScale() {
    product_image1 = $('#productimage1');
    if (product_image1.length == 1)
        scaleImage(product_image1);
    
    product_image2 = $('#productimage2');
    if (product_image2.length == 1)
        scaleImage(product_image2);
}

function selectItem(li)
{
  if (li.extra == null) return;
  $("div#content").load("/converter/ajax/product/" + li.extra + "/", undefined, function()
      {
	  afterLoadProduct();
      });
}

function selectNextItem()
{
  $("div#content").load("/converter/ajax/product/next/", undefined, function()
      {
	  afterLoadProduct();
      });
}

function selectPrevItem()
{
  $("div#content").load("/converter/ajax/product/prev/", undefined, function()
      {
	  afterLoadProduct();
      });
}

/*
* Find item handler.
*/
function findItem(val, hideResultsCallback)
{
  val = escape(val);
  $("div#content").load("/converter/ajax/product-find-item/?q=" + val,
     undefined, function()
      {
	afterLoadProduct();
        // Close dropdown if something was found
        if($("div#msg").length == 0)
        {
          hideResultsCallback();
        }
      });
}

/*
* Select conversion handler.
*/
function selectconversion(id)
{
  $("div#column_2").load("/converter/ajax/product-column2-by-cid/" + id + "/");
  $("div#column_3").load("/converter/ajax/product-column3-by-cid/" + id + "/", undefined, function(){
      // Notify Google Analytics to track current conversion
      urchinTracker("/converter/conversion/"+ $("div#currentConversion").text() );
  });

}

/*
* Save current conversion handler.
*/
function saveconversion(id)
{
  $("div#save_button_text").load("/converter/ajax/conversion-save/" + id);
  $("ul#save_button").hide("slow");
}

/*
* Remove conversion from user conversion list.
*/
function removeFromList(id,element)
{
  $.get("/converter/ajax/conversion-remove/" + id, function(data){
     if (data.substring(0,5) == "Error")
     {
        alert(data);
     }
  });
  $("tr#row"+id).hide("slow").remove();

  if ($(".info").length == 0)
  {
    // Last element, list is now empty
    $("div#id_convertlist").hide("slow");
  }
}

function saveproduct(id)
{
  $("div#save_button_text").load("/converter/ajax/product-save/" + id+"/")
  $("ul#save_button").hide("slow");
}

function removeConversion(conversion_id,product_item) {
    $.get("/converter/ajax/conversion-remove/" + conversion_id + "/", function(data) {
        if (data.substring(0,5) == "Error") {
            alert(data);
        } else {
            $.get("/converter/ajax/product-save/" + product_item + "/", function(data) {})
            $("#convertinfo" + conversion_id).hide("slow").remove();
        }
    });
}

function add(id)
{
  $("div#save_button_text").load("/converter/ajax/product-save/" + id+"/")
  $("ul#save_button").hide("slow");
}

/*
* Remove conversion from user conversion list.
*/
function removeProductFromList(id,element)
{
  $.get("/converter/ajax/product-remove/" + id+'/', function(data){
     if (data.substring(0,5) == "Error")
     {
        alert(data);
     }
  });
  $("tr#row"+id).hide("slow").remove();

  if ($(".info").length == 0)
  {
    // Last element, list is now empty
    $("div#id_convertlist").hide("slow");
  }
}

/*
* Scale single product image.
*/
function scaleImage(img)
{
  height = 110;
  width = 140;
  
  img = $(img);
  
  // Grab the image's dimensions
  var imgH = img.height();
  var imgW = img.width();

  // Find which dimension is scaled the most
  var scaleH = height / img.height();
  var scaleW = width / img.width();

  // Scale the image
  if (scaleH < scaleW) {
    img.height(height);
    img.width(Math.round(imgW * scaleH));
  } else {
    img.width(width);
    img.height(Math.round(imgH * scaleW));
  }
}

/*
* Ajax loading indicator.
*/
function loadingState(state)
{
  if(state)
  {
    $("img#loading").show();
  }
  else
  {
    $("img#loading").hide();
  }
}

/*
* Format autocomplete item
*/
function formatItem(row)
{
  return "<pre>" + row[0] + "</pre>";
}

/*
* Format selected value before returning to input box.
*/
function formatSelectedValue(value)
{
  var parts = value.split(",");
  var part = parts[0];

  if (part[part.length - 1] == ",")
    part = part.substr(0, part.length - 1)

  return part
}

/*
* Show more contacts.
*/
function showMoreContacts()
{
  $('div#morecontacts').modal();
  return false;
}
/*
* Show Popup window.
*/
function popUpWindow(url, height, width)
{
  var settings = {
            height: (height==undefined) ? 600 : height, // sets the height in pixels of the window.
            width: (width==undefined) ? 600 : width, // sets the width in pixels of the window.
            toolbar:0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
            scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
            status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
            resizable:1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
            left:0, // left position when the window appears.
            top:0, // top position when the window appears.
            center:1, // should we center the window? {1 (YES) or 0 (NO)}. overrides top and left
            createnew:1, // should we create a new window for each occurance {1 (YES) or 0 (NO)}.
            location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
            menubar:0 // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
        };

    // center the window
    if (settings.center == 1)
    {
        settings.top = (screen.height-(settings.height + 110))/2;
        settings.left = (screen.width-settings.width)/2;
    }

  // Prepare parameters
    parameters = "location=" + settings.location + ",menubar=" + settings.menubar + ",height=" + settings.height + ",width=" + settings.width + ",toolbar=" + settings.toolbar + ",scrollbars=" + settings.scrollbars  + ",status=" + settings.status + ",resizable=" + settings.resizable + ",left=" + settings.left  + ",screenX=" + settings.left + ",top=" + settings.top  + ",screenY=" + settings.top;

  var name = settings.createnew ? "_blank" : "PopUpWindow";
    window.open(url, name, parameters).focus();
    return false;
}

/*
* Conversion List Item Traversor
*/
function visitConversionItems(funcVisitor)
{
  var i = 1;
  var table = $("table#convertbl")[0];
  for(i=1;i<table.rows.length;i++)
  {
    // Call visitor for every row with checkbox element.
    funcVisitor($(table.rows[i].cells[0]).children("input")[0]);
  }
}

function visitConversionItemsAmount(funcVisitor)
{
  var i = 1;
  var table = $("table#convertbl")[0];
  for(i=1;i<table.rows.length;i++)
  {
    // Call visitor for every row with checkbox element.
    funcVisitor($(table.rows[i].cells[0]).children("input")[0], $(table.rows[i].cells[4]).find("input:text").val());
  }
}

function visitProductItems(funcVisitor)
{
  var i = 1;
  var table = $("table#producttbl")[0];
  for(i=1;i<table.rows.length;i++)
  {
    // Call visitor for every row with checkbox element.
    funcVisitor($(table.rows[i].cells[0]).children("input")[0]);
  }
}

/*
* Toggle conversion items checked state.
*   If first item is checked all items become unchecked.
*/
function toggleConversionItems()
{
  var first = true;
  var chk = false;
  visitConversionItems(function(chkbox)
  {
    if (first == true)
    {
      chk = !chkbox.checked;
      first = false;
    }
    chkbox.checked = chk;
  });
}

function toggleProductItems()
{
  var first = true;
  var chk = false;
  visitProductItems(function(chkbox)
  {
    if (first == true)
    {
      chk = !chkbox.checked;
      first = false;
    }
    chkbox.checked = chk;
  });
}

/*
* Open list as PDF or Excel
*/
/*
* Open list as PDF or Excel
*/
function openList(a)
{
  var selectedConversions = new Array();
  var selectedProducts = new Array();
  visitConversionItemsAmount(function(chkbox,amount)
  {
    if (chkbox.checked == true)
    {
      if ($(chkbox).attr('class')=="conversions-check") {
        selectedConversions.push([chkbox.id.replace("check",""),amount]);
      } else {
        selectedProducts.push([chkbox.id.replace("check",""),amount]);
      }
    }
  });

  // Clear previous parameters if any.
  var pindex = a.href.indexOf("?");
  if (pindex != -1)
  {
    a.href = a.href.substr(0,pindex);
  }
  a.href += '?';
  if(selectedConversions.length > 0)
  {
    var ids = "";
    var amounts = "";
    for(i=0;i<selectedConversions.length;i++)
    {
      ids += selectedConversions[i][0] + ",";
      amounts += selectedConversions[i][0] + "|" + selectedConversions[i][1] + ",";
    }
    a.href += "&list=" + ids;
    a.href += "&amounts_list=" + amounts;
  } else {
    a.href += "&list=";
    a.href += "&amounts_list=";
  }

  if(selectedProducts.length > 0)
  {
    var ids = "";
    var amounts = "";
    for(i=0;i<selectedProducts.length;i++)
    {
      ids += selectedProducts[i][0] + ",";
      amounts += selectedProducts[i][0] + "|" + selectedProducts[i][1] + ",";
    }
    a.href += "&product_list=" + ids;
    a.href += "&amounts_product_list=" + amounts;
  } else {
    a.href += "&product_list=";
    a.href += "&amounts_product_list=";
  }

  $("input:checked[name='export_settings']").each(function() {
    a.href += "&prefs=" + $(this).val();
  });

  if (!selectedConversions.length && !selectedProducts.length)
  {
      alert("No items selected!");
      return false;
  }

}
