var itemsPerPage = 10;
var visiblePage = 0;
var total_pages = 0;
var items;
var top_bottom = Array('top','bottom');
var CPOP_left_arrow_link = function(div_id){ return "<a href=\"#\" id=\"prevLink_"+div_id+"\"><img src=\"paginator/left_arrow.gif\" alt='&lt;' border='0' style='margin-right:3px;' height=9 width=9></a>";}
var CPOP_right_arrow_link = function(div_id){ return "<a href=\"#\" id=\"nextLink_"+div_id+"\"><img src=\"paginator/right_arrow.gif\" alt='&gt;' border='0' style='margin-right:3px;' height=9 width=9></a>";}
var CPOP_link_to_page = function(page,div_id){ return "<a href=\"#\"id=\"page_"+page+"_"+div_id+"\" onclick=\"return CPOP_goto_page("+page+");\" >"+(page+1)+"</a>";}

function CPOP_set_selected(page){
  for(var i=0 ; i<top_bottom.length; i++){
    var product_links = document.getElementById('product_links_'+top_bottom[i]);
    tags = product_links.getElementsByTagName('a');
    for( var k=1 ; k<tags.length-1 ; k++) tags[k].className = '';
    document.getElementById('page_'+page+'_'+top_bottom[i]).className = 'selected';
  }
  return true;
}

function CPOP_link_element(elem,page,div_id){
  var linkElement = document.getElementById(elem);
  linkElement.onclick=function() {
    CPOP_set_selected(eval(page));
    visiblePage = eval(page);
    CPOP_display_page();
    return false;
  }
}

function CPOP_goto_page(page){
  CPOP_set_selected(page);
  visiblePage = page;
  CPOP_display_page();
  return false;
}

function CPOP_generate_links(div_id){
  var link_a = new Array;
  link_a.push(CPOP_left_arrow_link(div_id));
  for( var k=0 ; k<total_pages ; k++) link_a.push(CPOP_link_to_page(k,div_id));
  link_a.push(CPOP_right_arrow_link(div_id));
  return link_a;
}

function CPOP_clear_navigation_links(){
  document.getElementById('product_links_top').innerHTML = "";
  document.getElementById('product_links_bottom').innerHTML = "";
}

function CPOP_link_top_bottom(){
  for(var i=0 ; i<top_bottom.length; i++){
    var link_a = CPOP_generate_links(top_bottom[i]);
    document.getElementById('product_links_'+top_bottom[i]).innerHTML = link_a.join('&nbsp;')
    first = 'Math.max(0,visiblePage-1)';
    last  = 'Math.min(Math.floor(items.length/itemsPerPage),visiblePage+1)';
    //link top
    CPOP_link_element('prevLink_'+top_bottom[i],first);
    //link bottom
    CPOP_link_element('nextLink_'+top_bottom[i],last);
  }
}

function CPOP_show_form(){
document.getElementById('product').innerHTML = "<p>We found <b>0 crossover boxes</b> matching the vehicle you've selected.</p><p>Although our search engine wasn't able to match a box to your truck, our product specialists are able to provide a customized recommendation if you <a href=\"contact_us.php\">fill out a simple form</a> to let us know more about your truck. (Please allow 1-2 business days for a reply)</p><p><b>Search Tips</b><br/>-Verify that you've selected the correct make, model and year for your truck.<br/>-Try selecting a different lid style or box size.</p>".split("\n").join("");
}

function CPOP_paginate(num){
  var product = document.getElementById('product');//cssQuery(selector);
  var divs = product.getElementsByTagName('div');
  items = new Array();
  for( var k=0 ; k<divs.length ; k++)
  {
    if(divs[k].className != "mmy0") continue;
    items.push(divs[k]);
  }
  if(items.length > 0)
  {
    itemsPerPage = num;
    total_pages = Math.floor(items.length/itemsPerPage)+1;
    visiblePage = 0;//reset visible page
    CPOP_link_top_bottom();
    CPOP_set_selected(0);
    CPOP_display_page();
  }
  else
  {
    CPOP_show_form();
  }
}

function CPOP_display_returned_number()
{
  var total = parseInt(arguments[1]);
  if(total > 0)
  {
    var message = 'We found  <b>'+arguments[1]+ ' Match';
    if(total > 1) message+='es.</b>'
    else
      message+='.</b>'
    document.getElementById(arguments[0]).innerHTML = message;
  }
  else
    document.getElementById(arguments[0]).innerHTML = '';
}

function CPOP_display_page() {
	//itterate through all of the items setting style.display to 'none' for
	//items that are below visiblePage+*itemsPerPage and above
	//[(visiblePage+1)*itemsPerPage]-1 while setting those in between to 'block'
	for(i=0;i<items.length;i++){
		items[i].style.display='block';
		if (i<visiblePage*itemsPerPage||i>((visiblePage+1)*itemsPerPage)-1) {
			items[i].style.display='none';
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////
/*

Usage examples
in a form
onsubmit="return add_to_cart_proxy({linkTrackVars: {products:[['1711111'],['1722222']]}, linkTrackEvents: {events: [['event3']]}});"

used in link

onclick="return add_to_cart_proxy({linkTrackVars: {products:[['1711111'],['1722222']], prop1:[['new']]}, linkTrackEvents: {events: [['event3']]}});"

*/

/*

  To create a link that triggers omniture code do the following:
  call link_to_omniture()
   as argument. see examples
  // Send single products single event
  // return add_to_cart_proxy({linkTrackVars: {products:[['1700002']]}, linkTrackEvents: {events: [['event3']]}});
  
  // Send Multiple products including merchandising category
  // return add_to_cart_proxy({linkTrackVars: {products:[['1700002'], ['1700002','evar2','Drills']]}, linkTrackEvents: {events: [['event3']]}});    
*/

function CPO_OMNITURE(){
  this.debug = false;
  // must be suplied at least two arguments
  // by default second argument will be returned if no matches are made
  this.format_value = function()
  {
    try{
      if(arguments.length < 2){throw "WrongNumberOfArguments";}
    }
    catch(e)
    {
      if(e == "WrongNumberOfArguments") return null;
    }
    arg = arguments;
    if(arg[0] == 'products')
    {
      var prod = arg[1];
      if(prod.length == 1) return ';'+prod[0]+';;;;'; //set only product
      else if(prod.length == 3) return ';'+prod[0]+';;;;'+prod[1]+'='+prod[2]; //set product with merch category
    }
    //return default value
    return arg[1];
  }
  
  this.process_omni_var = function()
  {
    if(arguments[0].length < 1) return 'None';
    else
      return arguments[0].join(',');
  }
  
  this.linkCode = function() {
    try{
      var verbose = true;
      if(!s_account) return true;// return true anc continue
      var q = s_gi(s_account);
      
      var args = arguments[0];
      
      for(var i in args)
      {
        //init empty array
        eval("q."+i+" = new Array()");
        var a_var = args[i];
        for (var key in a_var){
          eval("q."+key+" = new Array()");
          eval("q."+i+".push(\'"+key+"\')");
          for(var j in a_var[key])
          {
            var _value = this.format_value(key,a_var[key][j]);
            eval("q."+key+".push(\'"+_value+"\')");
          }
          eval("q."+i+".join(',')");
        }    
        //evaluate
        eval("q."+i+" = this.process_omni_var(q."+i+")");
      }
      q.tl();
      return false;
    }catch(e){
      if(this.debug){
        alert(e);
        alert("I will die gracefully!");
      }
      return false;
    }
  }
  this.parse_form_elements = function()
  {
    elems = arguments[0]
    args = arguments[1]
    for(var i in args){
      for (var key in args[i]){
        for(var j in args[i][key]){
          if(elems[args[i][key][j]])
          {
            sel = elems[args[i][key][j]];
            args[i][key][j] = sel[sel.selectedIndex].text;
          }
        }
      }    
    }
    return args;  
  }
}

//must be provided with sku
function add_to_cart_proxy()
{
  var sku = arguments[0];
  var om = new CPO_OMNITURE();
  return om.linkCode({linkTrackVars: {products:[[sku]]}, linkTrackEvents: {events: [['event3']]}});
}
/**

Usage
  pass elements
"return link_to_omniture_custom(document.forms['make_model_year'].elements,{linkTrackVars: {eVar3: ['make','model','year'], eVar4: ['lid_style','box_size']},linkTrackEvents: {events: [['event4']]}});"

**/
function update_product_form_proxy()
{
  if(arguments[0])
  {
    var om = new CPO_OMNITURE();
    args = om.parse_form_elements(arguments[0],{linkTrackVars: {eVar3: ['make','model','year'], eVar4: ['lid_style','box_size']},linkTrackEvents: {events: [['event4']]}});
    return om.linkCode(args);
  }
}

