var item_options = [];
var item_selects = [];
var in_stock_options = [];

$(document).ready(function() {	
//get ns data
NSitemID = $("input[name='id']").val();
NSstock = window['Item' + NSitemID + '_avail'];
NSprices = window['Item' + NSitemID + '_prices'];

if (NSstock !== undefined || NSprices !== undefined) {
  build_option_array();
  build_option_selector();
	in_stock_options = get_all_choices(item_options);
}
if ($('#gallery').length > 0) {
  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=53231618@N07&format=json&jsoncallback=?", add_action_feed);
}
//  add_subscribe_form();

	$('.products td table tr').each(function() {
		$(this).find('ul').last().addClass('last');
	});

	$('.item_option li.selected a').click(function() { return false; });
	$('.item_option li:not(.selected) a').click(function() {
		var selectID = $(this).parents('ul').siblings('select').attr('id');
		var parentID = $(this).parents('ul').attr('id');
		var value = $(this).attr('href').substr($(this).attr('href').indexOf('#') + 1);
		var selectVal = ($(this).attr('title') != '') ? $(this).attr('title') : $(this).text();
		$('#' + selectID).val(value); // update select field in the form
		$(this).parent().addClass('selected').siblings('li').removeClass('selected');
		$(this).parents('ul').siblings('select').trigger('change');
		$('#' + selectID + '_fs_lbl .sel').html(selectVal + ' <a href="#'+ selectID +'" class="clear">x</a>');
		var position;
		var selected;
		var availables;
		var selectedTmp = [];
		for (var s in item_selects) {
			availables = check_group(item_selects[s]);
			$('#option_' + item_selects[s] + ' li').removeClass('oos');
			for (var x in item_options[s]) {
				if ($.inArray(item_options[s][x], availables[s]) == -1) {
					$('#option_' + item_selects[s] + ' li' + '#' +item_selects[s] + '_' + item_options[s][x]).addClass('oos');
				}
			}
		}
		return false;
	});
	$('.sel a.clear').live('click', function() {
		var selectID = $(this).attr('href').substr(1);
		$('#option_' + selectID + ' li').removeClass('selected');
		$(this).parents('.sel').html('');
		for (var s in item_selects) {
			availables = check_group(item_selects[s]);
			$('#option_' + item_selects[s] + ' li').removeClass('oos');
			for (x in item_options[s]) {
				if ($.inArray(item_options[s][x], availables[s]) == -1) {
					$('#option_' + item_selects[s] + ' li' + '#' +item_selects[s] + '_' + item_options[s][x]).addClass('oos');
				}
			}
		}
		return false;
	});

$('#n_store li, .button').hover(function(event) {$(this)[((event.type == 'mouseenter') ? 'add' : 'remove') + 'Class']('hover');});
$('.button').mousedown(function(){$(this).addClass('active');}).mouseleave(function(){$(this).removeClass('active');});

$('input:disabled').addClass('disabled');

	$(".n_tabs li").each(function() {
		var tab_id = $(this).children("a").attr("href");
		if (!$(tab_id).text()) {
		  $(this).hide();
	  }
	});
$(".n_tabs").tabs();

	$("#features").tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 10000);
	$("#twitter").tweet({count: 1,username: "tadgear",loading_text: "Loading tweets..."});

// replace &GT with &raquo;
	if ($('#n_trail').length > 0) { 
		$('#n_trail').html($('#n_trail').html().replace(/&gt;/g, '&raquo;'));
	}
	
// build product image carousel
	if ($(window['item_images']).length > 1) {
		build_image_viewer(window['item_images']);
	}

	$('#preview .thumbs ul li').click(function() {
		var i = $('#preview .thumbs ul li').index(this);
		$(this).addClass('selected').siblings('li').removeClass('selected');
		$($('#preview .big ul li').get(i)).addClass('selected').siblings('li').removeClass('selected');
	});

	$('#big .thumbs ul li').click(function() {
		var i = $('#big .thumbs ul li').index(this);
		$(this).addClass('selected').siblings('li').removeClass('selected');
		$($('#big .big ul li').get(i)).addClass('selected').siblings('li').removeClass('selected');
	});

	$('#preview .lbv a').click(function (e) {
		$('#big').modal({
			maxHeight : $(window).height() - 40,
			maxWidth : $(window).width() - 40,
			overlayClose : true,
			onShow : function() {
				var w = $('#big').width() - 170;
				var h = $(window).height() - 60;
				$('#big .big li').css({'width' : w, 'height' : h });
				$('#big .big').css({'height' : $(window).height() - 64});
				$("#big .big").jCarouselLite({
					btnPrev: ".big .prev",
					btnNext: ".big .next",
					visible: 1,
					btnGo: [".thumbs .1", ".thumbs .2", ".thumbs .3", ".thumbs .4", ".thumbs .5", ".thumbs .6", ".thumbs .7", ".thumbs .8", ".thumbs .9", ".thumbs .10", ".thumbs .11", ".thumbs .12", ".thumbs .13", ".thumbs .14", ".thumbs .15"]
				});
				if (w > h) {
				  $('#big .big li img').css({'height' : '100%'});
				} else {
				  $('#big .big li img').css({'width' : '100%'});
				}
			}
		});
		return false;
	});

	$('input.inputreq').keypress(function(e) {
		console.log('test2');
		c = e.which ? e.which : e.keyCode;
		if (c == 13) {
			console.log('test');
			$(this).blur();
			$('#submitter').focus().click();
		}
	 });

/* category view sort */
//var qparams = $.deparam.querystring(window.location.href);
	var qparams = '';
	$(".sort_select").html('<select name="sort_by" class="sort_order"><option value="default">New Arrivals</option><option value="name_asc" >Name (A to Z)</option><option value="name_desc">Name (Z to A)</option><option value="price_asc">Price (Low to High)</option><option value="price_desc">Price (High to Low)</option></select>');
	if (qparams.length == 0) {
		$('.sort_order').val('default');
	} else if (qparams.sort1 == "Item_NAME") {
		if (qparams.sort1desc == "F") {
			$('.sort_order').val('name_asc');
		} else if (qparams.sort1desc == "T") {
			$('.sort_order').val('name_desc');
		}
	} else if (qparams.sort1 == "Item_ONLINECUSTOMERPRICE") {
		if (qparams.sort1desc == "F") {
			$('.sort_order').val('price_asc');
		} else if (qparams.sort1desc == "T") {
			$('.sort_order').val('price_desc');
		}
	}
	$("select.sort_order").change(function(){
		if ($(this).val() == "default") {
			window.location.href = $.param.querystring(window.location.href, "sort1desc=&sort1=");
		} else if ($(this).val() == "name_asc") {
			window.location.href = $.param.querystring(window.location.href, "sort1desc=F&sort1=Item_NAME");
		} else if ($(this).val() == "name_desc") {
			window.location.href = $.param.querystring(window.location.href, "sort1desc=T&sort1=Item_NAME");
		} else if ($(this).val() == "price_asc") {
			window.location.href = $.param.querystring(window.location.href, "sort1desc=F&sort1=Item_ONLINECUSTOMERPRICE");
		} else if ($(this).val() == "price_desc") {
			window.location.href = $.param.querystring(window.location.href, "sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE");
		}
	});
/* ns dom manipulation */
  if ($('#tad_content').length < 1) {
	  $('body').attr('id', 'customer_center');
	}
	
  $("#n_product .portletHandle table tr:first").addClass("active_tab");
	
	if (document.URL.indexOf("thanks") != -1) {
	  $("#ordersummary_total").closest('table').attr('id', 'carttable').find('tr').first().attr('id', 'carttableheader');
		$("#continue.bgbutton").closest('table').attr('align', 'right');
	}

});
/* end INIT */
function add_action_feed(data) {
// Our very special jQuery JSON fucntion call to Flickr, gets details
// of the most recent 20 images
    // Start putting together the HTML string
    var htmlString = "<ul>";

    for (var i = 0;  i <= 10; i++) {
			var item = data.items[i];
			var imgSource;
			var cssclass;
			if (i == 0 || i == 5 || i == 10) {
				cssclass = "large";
        imgSource = (item.media.m).replace("_m.jpg", ".jpg");		  
			} else if (i == 4 || i == 9) {
				cssclass = "small last";
        imgSource = (item.media.m).replace("_m.jpg", "_s.jpg");		  
			} else {
				cssclass = "small";
        imgSource = (item.media.m).replace("_m.jpg", "_s.jpg");		  
			}
        htmlString += '<li class="box ' + cssclass + '"><a href="' + item.link + '" target="_blank">';
        htmlString += '<img title="' + item.title + '" src="' + imgSource;
        htmlString += '" alt="'; htmlString += item.title + '" />';
        htmlString += '</a></li>';
		}
		htmlString += "</ul>";
    // Now start cycling through our array of Flickr photo details
    // Pop our HTML in the #images DIV
    $('#gallery .content').html(htmlString);
   
    // Close down the JSON function call
}
function add_subscribe_form() {
	try {
			var place = document.getElementById("subscribe");
			if(place) {
				$('#subscribe iframe').remove();
				var ifr = document.createElement("iframe");
				var src = "http://tripleaughtdesign.com/site/newsletter_signup.html";
	    	if(document.URL.indexOf('subscribed') != -1) {
				  src = "http://tripleaughtdesign.com/site/newsletter_thanks.html";
				}
				ifr.setAttribute("src", src);
				ifr.setAttribute("width", "475");
				ifr.setAttribute("height", "40");
				ifr.setAttribute("scrolling", "no");
				ifr.setAttribute("frameborder", "0");
				place.appendChild(ifr);
			}
  } catch(e) {}
}
function check_group(id) {
	var criteria;
	var availables;
	var temp_criteria = [];
  for (var n in item_selects) {
		if (item_selects[n] == id) {
			temp_criteria.push('[0-9]+');
		} else {
			if ($('#option_' + item_selects[n]).find('.selected').length > 0) {
		    temp_criteria.push($('#option_' + item_selects[n]).find('.selected a').attr('href').substr(1));
			} else {
		  	temp_criteria.push('[0-9]+');
			}
		}
	}
	criteria = temp_criteria.join(":");
  var availables = is_available(criteria); // update other items availability
	return availables;
}
/* product selector */
// build a reliable stock status array out of all possible choices array
var is_in_stock = function(opt) {
  var result = true;
  var stock = NSstock;
  for (var i in stock) {
    if (i.indexOf(opt) != -1 ) {
      result = false;
    }
  }
  return result;
};
// build all possible choices array
var get_all_choices = function(m) {
  var map = (typeof(m) === 'undefined' ) ? [] : $.extend(true, [], m);
  var tmp = [];
  var result = [];
  if (map.length > 1) {
    for (var o in map[0]) {
       for (var b in map[1]) {
        tmp.push(map[0][o] + ':' +map[1][b]);
      }
    }
    map.splice(0, 2, tmp);
    result = get_all_choices(map);
  } else {
    for (var oo in map[0]) {
      result[map[0][oo]] = is_in_stock(map[0][oo]);
    }
  }
  return result;
};
// build all options with child choices array
var build_option_array = function() {
  $('select[id^="custcol"]').each(function(i) {
      item_selects.push($(this).attr("id"));
      item_options[i] = [];
      $(this).children('option').each(function() {
      if ($(this).val()) {
        item_options[i].push($(this).val());
      }
    });
    i++;
  });
};
// now build an array of items that are in stock, per choice available... fucking a.
var is_available = function(opt) {
  var availables = new Array(item_selects.length);
  var stock = get_all_choices(item_options);
  for (var i in stock) {
    if (stock[i] === true) { // only check options that are known to be available
      if (opt !== undefined) { // test it for our choice in select
        var r = new RegExp("^" + opt + "$");
				if (i.match(r) !== null) {
				  var tmp = i.split(':');
          for (var s in tmp) {
            availables[s] = (availables[s] !== undefined && availables[s].constructor.toString().indexOf("Array") != -1 ) ? availables[s] : [];
            if ($.inArray(tmp[s], availables[s]) == -1) {
              availables[s].push(tmp[s]);
            }
          }					
				}
      } else { // test it for all choices
        var tmp = i.split(':');
        for (var s in tmp) {
          availables[s] = (availables[s] !== undefined && availables[s].constructor.toString().indexOf("Array") != -1 ) ? availables[s] : [];
          if ($.inArray(tmp[s], availables[s]) == -1) {
            availables[s].push(tmp[s]);
          }
        }
      }
    }
  }
  return availables;
};

var build_option_selector = function() {
  var availables = is_available();
  $(item_options).each(function(i) {
		var selectID = item_selects[i];
		var selectContainer = $('#'+selectID).parent();
		var newSelector = $('<ul class="item_option" id="option_'+ selectID +'" />');
		var newOptions = '';
		var classes = '';
		selectContainer.parent().prepend($('#' + selectID + '_fs_lbl'));
		$('#' + selectID + '_fs_lbl').append('<span class="sel" />');
		$('#' + selectID + '_fs_lbl a.smalltextnolink').append(':');
		selectContainer.parent().siblings().hide();  
		$('#'+selectID).hide();
			$(item_options[i]).each(function(x) {
				if (item_options[i].length == 1) {
					classes = ' selected';
					$('#' + selectID).val(item_options[i][x]);
					$('#' + selectID + '_fs_lbl .sel').html($('#' + selectID + ' option[value=' + item_options[i][x]+']').text());
				}
				if (availables[i] !== undefined && $.inArray(item_options[i][x], availables[i]) != -1) {
					if (item_selects[i] === "custcol1" || item_selects[i] === "custcol2") {
						newOptions += ('<li class="o' + item_options[i][x] + classes + '" id="' + selectID + '_'+ item_options[i][x] +'"><a href="#' + item_options[i][x] + '" title="' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() + '"></a><span title="' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() + '"></span></li>\n');
					} else {
						newOptions += ('<li class="o' + item_options[i][x] + classes + '" id="' + selectID + '_'+ item_options[i][x] +'"><a href="#' + item_options[i][x] + '">'+ $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() +'</a><span>' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() +'</span></li>\n');					
					}
				} else {
					if (item_selects[i] === "custcol1" || item_selects[i] === "custcol2") {
						newOptions += ('<li class="o' + item_options[i][x] + ' oos" id="' + selectID + '_'+ item_options[i][x] +'"><a href="#' + item_options[i][x] + '" title="' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() + '"></a><span title="' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() + '"></span></li>\n');
					} else {
						newOptions += ('<li class="o' + item_options[i][x] + ' oos" id="'+ selectID + '_'+ item_options[i][x] +'"><a href="#' + item_options[i][x] + '">'+ $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() +'</a><span>' + $('#' + selectID+ ' option[value=' + item_options[i][x]+']').text() +'</span></li>\n');
					}
				}
			});
		newSelector.append(newOptions);
		selectContainer.append(newSelector);
  });
};
function build_image_viewer(images) {
  var carousel_preview;
	var preview_images = [];
	var preview_thumbs = [];
	var carousel_big;
	var big_images = [];
	var big_thumbs = [];
  for (var i in images) {		
	  var t = (images[i][0] != "") ? images[i][0] : images[i][1]; // use big image if there is no thumbnail
		var p = images[i][1];
		var d = (images[i][2] !== "") ? images[i][2] : '' ;
		var b = images[i][3];
    var descr = '';
		if (d != "") {
			var descr = '<div class="desc">'+ d +'</div>';
		}
		if (b != "") {
		  var lbbtn = '<div class="lbv"><a href="#"></a></div>';
			if (big_images.length > 0) {
		  big_images.push('<li><img src="' + b + '" alt="' + d + '" />' + descr + '</li>');
			big_thumbs.push('<li class="' + big_images.length + '"><img src="' + t + '" alt="' + d + '" /></li>');
			} else {
		  big_images.push('<li class="selected"><img src="' + b + '" alt="' + d + '" />' + descr + '</li>');
			big_thumbs.push('<li class="selected 1"><img src="' + t + '" alt="' + d + '" /></li>');
			}
		} else {
			var lbbtn = '';
		}
		if (i == 0) {
		  preview_images.push('<li class="selected"><img src="' + p + '" alt="' + d + '" />'+ lbbtn + descr +'</li>');
			preview_thumbs.push('<li class="selected"><img src="' + t + '" alt="' + d + '" width="75" height="100" /></li>')
		} else {
		  preview_images.push('<li><img src="' + p + '" alt="' + d + '" />'+ lbbtn + descr + '</li>');
			preview_thumbs.push('<li><img src="' + t + '" alt="' + d + '" width="75" height="100" /></li>')
		}
	}
	if (big_images.length > 0) {
	  carousel_big = $('#big');
		carousel_big.find(".big").prepend('<div class="prev" /><div class="next" />')
		carousel_big.find(".big ul").html(big_images.join('\n'));
		carousel_big.find(".thumbs ul").html(big_thumbs.join('\n'));
	}
	if (preview_images.length > 1) {
	  carousel_preview = $('#preview');
		carousel_preview.find(".big ul").html(preview_images.join('\n'));
		carousel_preview.find(".thumbs ul").html(preview_thumbs.join('\n'));
	  carousel_preview.find(".thumbs ul").jcarousel({
	    buttonNextHTML: '<div class="control"><span></span></div>',
		  buttonPrevHTML: '<div class="control"><span></span></div>',
	  	buttonNextEvent: 'click',
  		buttonPrevEvent: 'click',
			itemFallbackDimension: 75
		});
		$('.control').click(function(e) {
		  e.preventDefault();
		});
	}
}
function fIEiO(a, s, start) {
    var len = a.length >>> 0;
 
    var from = Number(start) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;
 
    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === s)
        return from;
    }
    return -1;
  };

