var gal_container_id = '#gallery-container';

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length >>> 0;

		var from = Number(arguments[1]) || 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] === elt)
				return from;
		}
		return -1;
	};
}


Array.prototype.unique = function() {
	var a = [];
	var l = this.length;
	for(var i = 0; i < l; i++) {
		for(var j = i + 1; j < l; j++) {
			// If this[i] is found later in the array
			if (this[i] === this[j]) {
				j = ++i;
			}				
		}
		a.push(this[i]);
	}
	return a;
};

Array.prototype.intersection = function( setB ) {
	var setA = this;

	var setA_seen = {};
	var setB_seen = {};
	for ( var i = 0; i < setB.length; i++ ) {
			setB_seen[ setB[i] ] = true;
	}

	var intersection = [];
	for ( var i = 0; i < setA.length; i++ ) {
			if ( !setA_seen[ setA[i] ] ) {
					setA_seen[ setA[i] ] = true;
					if ( setB_seen[ setA[i] ] ) {
							intersection.push( setA[i] );
					}
			}
	}

	return intersection;
};

String.prototype.trim = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function isdefined (variable) {
	return (typeof(variable) !== "undefined") ? true : false;
}

function gup(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );

	if( results == null )
		return "";
	else
		return results[1];
}

function update_options(att_id,att_val) {
	var proceed = false;
	var array_match = [], temp = [];
	var update_size_popup = false;

	for (var i in json_config.attributes) {
		var item = json_config.attributes[i];
		if (proceed) {
			last = false;
			$j('#attribute' + item.id).val('');
			var temp_item = {};
			temp_item['id'] = item.id;
			temp_item['label'] = item.label;
			temp_item['options'] = [];
			var arr_length = item.options.length;
			for (var i = 0; i < arr_length; i++) {
				if (item.options[i].products.intersection(array_match).length > 0) {
					temp_item['options'].push(item.options[i]);
				}
			}

			if (item.code.toLowerCase() == 'size') {
				if (temp_item['options'].length > 0) {
					$j('#att_elem_' + item.id).html(get_size_code(temp_item));
					update_size_popup = true;
				}

				if ($j('#attribute' + item.id).val() == '') {
					$j('#attribute' + item.id).val($j('.size_select option:selected').val());
				}
			} else if (item.code.toLowerCase() == 'color') {
				if (temp_item['options'].length > 0) {
					$j('#att_elem_' + item.id).html(get_color_code(temp_item));
				}
			}
		} else {
			proceed = (item.id == att_id);
			var arr_length = item.options.length;

			for (var i = 0; i < arr_length; i++) {
				if (item.options[i].id == $j('#attribute' + item.id).val()) {
					if (array_match.length > 0) {
						temp = item.options[i].products.intersection(array_match);
						array_match = temp;
					} else {
						array_match = item.options[i].products;
					}
				}
			}
		}
	}


	//update_price();
	update_product_image();
}

function update_price () {
	//var local_price = parseFloat($j('.price:not(.line-through)').text());
	var new_price = parseFloat(product_price);

	for (var i in json_config.attributes) {
		var item = json_config.attributes[i];
		var att_val = $j('#attribute' + item.id).val();
		if (att_val != '') {
			var len = item.options.length;
			for (var j = 0; j < len; j++) {
				if (item.options[j].id == att_val) {
					new_price += parseFloat(item.options[j].price);
					break;
				}
			}
		}
	}

	$j('.price:not(.line-through)').text('$' + new_price.toFixed(2));
}

function is_array(input){
	return typeof(input)=='object'&&(input instanceof Array);
}

function preselect_first_size() {
	for (var i in json_config.attributes) {
		var att = json_config.attributes[i];
		if (att.code == 'size') {
			var op_length = att.options.length;
			for (var j = 0; j < op_length; j++) {
				if (check_if_saleable(att.id, att.options[j].id, att.options[j].products)) {
					size_change(att.id,att.options[j].id);
					return true;
				}
			}
		}
	}
}

function size_change(att_id,size_id) {
	$j('#attribute' + att_id).val(size_id);
	$j('.size-op').removeClass('selected-size');
	$j('.size_' + size_id).addClass('selected-size');
	current_sel[att_id] = size_id;
	update_options(att_id,size_id);
}


function color_select(att_id,color_id) {
	$j('.color-name').hide();
	$j('.cname_' + color_id).show();
	$j('#attribute' + att_id).val(color_id);
	$j('.cw').removeClass('selected-color');
	$j('.cw_' + color_id).addClass('selected-color');
	current_sel[att_id] = color_id;
	update_options(att_id,color_id);
}

function check_if_saleable(att_id, value_id, products_per_option) {
	// check if product ids for current option are all saleable 
	// with previous options already stored in current_sel
	
	var prods = [];
	for (var i in current_sel) {
		if (i != att_id) {
			// get items from main json_config that correspond to selections
			for (var j in json_config.attributes) {
				var item = json_config.attributes[j];
				if (i == item.id) {
					var op_len = item.options.length;
					for (var op = 0; op < op_len; op++) {
						if (item.options[op].id.toString() == current_sel[i].toString()) {
							var item_prods = item.options[op].products;
							var len = item_prods.length;
							for (var idx = 0; idx < len; idx++) {
								prods.push(item_prods[idx]);
							}
						}
					}
				}
			}
		}
	}
	
	// check if any products in the perspective option 
	// are in the selected option products
	var prod_int = prods.intersection(products_per_option);
	var prod_int_len = prod_int.length;
	if (prods.length > 0 && prod_int_len > 0) {
		for (var int_idx = 0; int_idx < prod_int_len; int_idx++) {
			//alert(prod_int[int_idx]);
			if (json_config.nonsaleable.indexOf(prod_int[int_idx]) > -1) {
				return false;
			}
		}
	}
	
	return true;
}

function get_size_code(item) {
	var arr_length = item.options.length;
	var default_id = '';
	
	// Check if only one size
	// Accessories should not have size option appear
	if ((arr_length == 1) && (item.options[0].label == 'OS')) {
		config_html_code = '<input type="hidden" id="attribute' + item.id + '" name="super_attribute[' + item.id + ']" class="required-entry hid_attr" value="' + item.options[0].id + '">';
	} else {
		var config_html_code = '<p class="plabel left">Size</p>';
		config_html_code += '<div class="right swatch_select">';

		for (var i = 0; i < arr_length; i++) {
			if (!check_if_saleable(item.id, item.options[i].id, item.options[i].products)) {
				config_html_code += '<span class="t-size1 disabled left"><span>' + item.options[i].label + '</span><em></em></span>';
			} else {
				config_html_code += '<a href="#" class="size_change" id="att_' + item.id + '" rel="' + item.options[i].id + '">';
				if (i % 1 == 0) {
					config_html_code += '<span class="size-op t-size1 left size_select size_' + item.options[i].id + '" ><span>' + item.options[i].label + '</span></span>';
				} else {
					config_html_code += '<span class="size-op t-size2 left size_select size_' + item.options[i].id + '" ><span>' + item.options[i].label + '</span></span>';
				}
				config_html_code += '</a>';
			}

		}

		config_html_code += '<input type="hidden" id="attribute' + item.id + '" name="super_attribute[' + item.id + ']" class="required-entry hid_attr" value="' + default_id + '">';
		config_html_code += '<div class="cl">&nbsp;</div>'
		config_html_code += '</div>';
	}

	return config_html_code;
}

function get_color_code(item) {
	var config_html_code = '<p class="plabel left">Color</p>';

	var arr_length = item.options.length;
	var default_id = '';
	var selected_class = '', color_name = '';
	config_html_code += '<div class="right swatch_select">';
	for (var i = 0; i < arr_length; i++) {
		color_name = item.options[i].label.toLowerCase().replace(/([^a-z0-9])/g,'-');
		config_html_code += '<span class="left" id="#cw_' + item.options[i].id + '">';
		config_html_code += '<a href="#" class="color_select" id="att_' + item.id + '" rel="' + item.options[i].id + '">';
		if (color_swatches[item.options[i].id]) {
			config_html_code +=  '<img src="' + color_swatches[item.options[i].id] + '" alt="' + color_name + '" width="19" height="19" class="cw_' + item.options[i].id + ' cw' + selected_class + '" rel="' + item.options[i].label + '" />';
		} else {
			config_html_code +=  '<img src="' + color_swatches[0] + '" alt="' + item.options[i].label +'" width="19" height="19" class="cw_' + item.options[i].id + ' cw' + selected_class + '" rel="' + item.options[i].label + '" />';
		}
		config_html_code += '</a></span>';
	}
	for (var i = 0; i < arr_length; i++) {
		config_html_code += '<p class="cname_' + item.options[i].id + ' color-name left" style="display:none;">' + item.options[i].label + '</p>';
	}

	config_html_code += '<input type="hidden" id="attribute'+ item.id + '" name="super_attribute[' + item.id + ']" class="required-entry hid_attr" value="' + default_id + '">';
	config_html_code += '</div>';

	return config_html_code;
}
	
function specs() {
	$j('.spec_div').toggle();
}

function go_page (page_action) {
	show_page(page_num + page_action);
}

function go_image (image_action) {
	if (((cur_image + image_action) >= 0) && ((cur_image + image_action) < image_list.images.length)) {
		var offset = (cur_page-1) * per_page;
		var limit = ((cur_page-1) * per_page) + per_page;

		acdc_updateMainImage(cur_image + image_action);

		if (cur_image >= limit) {
			show_page(page_num + 1);
		}

		if (cur_image < limit) {
			show_page(page_num - 1);
		}
	}
}

function update_image_list(new_image_list) {
	page_num = 1;
	cur_page = 1;
	cur_image = 0;
	image_list = new_image_list;
}

function acdc_updateMainImage(image_id) {

	var code = '<a href="' + image_list.images[image_id].large + '" class="jqzoom" id="jqzoom' + image_id + '">';
	code += '<img src="' + image_list.images[image_id].medium + '" alt="' + image_list.images[image_id].label + '" />';
	code += '</a>';

	//$j('#basket').css('margin-top','32px');
	$j('#basket').html(code);

	$j("#jqzoom" + image_id).jqzoom(options);
	cur_image = image_id;
		
	$j(gal_container_id).find('li').removeClass('current');
	$j('#is_' + image_id).addClass('current');
}

function acdc_previewMainImage(image_id) {
	$j('#basket').append('<div class="prev_image" id="temp_img_' + image_id + '"><img src="' + image_list.images[image_id].medium + '" /></div>');
}

function load_large_view() {
	var code = '';
	var limit = image_list.images.length;
	var first_large = '';
	for (var i = 0; i < limit; i++) {
		if (i == 0) {
			first_large = image_list.images[i].lv;
		}
		code += '<li><a href="#" class="lv_t" rel="' + image_list.images[i].lv + '">';
		code += '<img src="' + image_list.images[i].small + '" alt="' + image_list.images[i].label + '" />';
		code += '</a></li>';
	}

	$j('#lv-thumbs').html(code);
	$j('#lv-main').attr('src',first_large);
	$j('.lv_t').bind('click', function(e) {
		e.preventDefault();
		$j('#lv-main').attr('src',$j(this).attr('rel'));
	});
	$j('.lv_close').bind('click', function(e) {
		e.preventDefault();
		$j('.large-view').hide();
	});
}

function fbs_click(url) {
	window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function open_twitter_window(url, text) {
	window.open('http://twitter.com/share?url=' + url + '&text=' + text,'twitter','width=500,height=300');
}
