//make uniqID
var uid = (
	function(){
		var id=0;
		return function(){
			return id++ ;
		};
	}
)();

//emulate popup function...
var popWindow = function(u,w,h,popEl){
	if(!popEl){
		e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
		if(e == 'png' || e == 'gif' || e == 'jpg')
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><img src=\""+ u +"\" width=\"" + w + "\" height=\"" + h + "\" border=\"0\" /></div>",{overlay:20});
		else
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><iframe src=\""+ u +"\"  width=\"" + w + "\" height=\"" + h + "\" border=\"0\" frameborder=\"0\"></iframe></div>",{overlay:20});
	}
	popEl.modal({
			onOpen: function (dialog) {
						dialog.data.addClass('alert');
						dialog.container.css('height','auto');
						dialog.overlay.fadeIn('normal', function () {
							dialog.container.show('normal', function () {
								dialog.data.slideDown('normal'); // See Other Notes below regarding
														   // data display property and
														   // iframe details
							});
						});
					},
			onClose: function (dialog) {
						dialog.data.slideUp('normal', function () {
						  dialog.container.hide('normal', function () {
							dialog.overlay.fadeOut('normal', function () {
							  $.modal.close(); // must call this to have SimpleModal
											   // re-insert the data correctly and
											   // clean up the dialog elements
							});
						  });
						});
					}
	});
	$("#modalContainer").css('width',w).css('margin-left',(w / 2) * -1).css('height',h).css('margin-top',(h / 2) * -1); 
}

//var buildPriceUI = function(){}

//get selection
var getPriceSelection = function(){
	sel_color = $(this).find('select.color').val();
	sel_size = $(this).find('select.size').val();
	
	$(this).parents('.prices').children('.price_line').each(function(){
		i = $(this).find('.ref').text().split('/');
		ref = i[0];
		size = i[i.length - 1];
		color = new Array();
		for(j=1;j<i.length - 1;j++){
			color[color.length] = i[j];
		}
		color = color.join('/');
		
		if(sel_size == size && sel_color == color){
			$(this).find('.dynPriceUI').html($(this).find('span.price').html());
		}
	});
}

//build UI menus
var buildPriceUI = function(obj){
	obj.each(function(){
		var selectedPrice = "";
		var colorSelect = $('<select class="color" />').change(getPriceSelection);
		var sizeSelect = $('<select class="size" />').change(getPriceSelection);
		$(this).children('.price_line').each(function(){

			//get vars
			i = $(this).find('.ref').text().split('/');
			
			ref = i[0];
			size = i[i.length - 1];
			color = new Array();
			for(j=1;j<i.length - 1;j++){
				color[color.length] = i[j];
			}
			color = color.join('/');

		
			//build size
			if(!sizeSelect.find('option[value="' + size + '"]').length){
				o = $("<option />").val(size).text('maat: ' + size);
				sizeSelect.append(o);
			}
			
			//build color select
			if(!colorSelect.find('option[value="' + color + '"]').length){
				o = $("<option />").val(color).text(color);
				colorSelect.append(o);
			}
			
			if(!selectedPrice)
				selectedPrice = $(this).find('span.price').html();
		});

		$(this).append($('<form class="pirceselector clear" />').submit(function(e){
			e.preventDefault();
			
			sel_am = 1;//$(this).find('input.input').val();
			sel_color = $(this).find('select.color').val();
			sel_size = $(this).find('select.size').val();
			
			$(this).parents('.prices').children('.price_line').each(function(){
				i = $(this).find('.ref').text().split('/');
				
				ref = i[0];
				size = i[i.length - 1];
				color = new Array();
				for(j=1;j<i.length - 1;j++){
					color[color.length] = i[j];
				}
				color = color.join('/');
			
				if(sel_size == size && sel_color == color){
					o = $(this).find('.amount input').attr('name');
					
					self.location.href='/?module=shop&cart=Y&' + o + '=' + sel_am;
				}
			});
			
			return false;
		}));
					   
		if($(this).children('.price_line').length > 1){
			
			p = '<div class="price clear"><span class="price"><span class="new_price">' + selectedPrice + '</span></span> <span class="tax">incl. 19% BTW</span><span class="sold_out stock"></span> </div>';
			
			u = $('<div class="ui"></div>').append(sizeSelect).append(colorSelect).append('<input type="text" class="input" value="" size="2" /><input type="submit" class="order_button" value="&raquo; Bestel" />');
			$(this).find('form').append(u).before(p);
		}else{
			$(this).find('.price_line').css('display','block');
		}
	});
}

//make same height
var make_same_height = function(selector){
	var max_height = 0;
	$(selector).each(function(){
		if($(this).height() > max_height){
			max_height = $(this).height();
		}
	});
	$(selector).height(max_height);	
}


$(document).ready(function(){

/*	-------------------------------------------
	MENU
	----------------------------------------- */

	$("#menu ul li").not('#menu ul ul li').hover(
		function(){
			i = $(this).children('ul:eq(0)');
			if(i.is(":hidden"))
				i.show();
		},
		function(){
			i = $(this).children('ul:eq(0)');
			if(i.is(":visible"))
				i.hide();
		}
    );

/*	-------------------------------------------
	ADD SOME PADDING/MARGIN
	----------------------------------------- */

	$(".article img[align='left']").css('margin-right','10px');
	$(".article img[align='right']").css('margin-left','10px');
	
/*	-------------------------------------------
	CHANGE STORE MODULE
	----------------------------------------- */
	
	if($("#left_column .store_module").length){

		//remove title from photoalbums
		//$('.photoalbum_module').parents('.article:eq(0)').find('div.title').remove();
		//$('#left_column > div.article.default:eq(0) div.title:eq(0)').remove();
		//$('#left_column div.store_module > div.article.default:eq(0) div.title:eq(0)').remove();
		//$('#left_column div.article:eq(0) div.content').removeClass('clear');

		$('.store_module div.listing div.spec_group_menu select').change(function(){
			$(this).parents('form').trigger('submit');
		});

		buildPriceUI($('.store_module div.article .prices'));

		if($("#left_column .store_module .prices .price_line").length > 1){
			//make price line.
			//$("#left_column .store_module .item_details .prices").height($("#left_column .store_module .item_details .priceselector").height() + $("#left_column .store_module .item_details .prices .price_line:eq(0)").height()).css('overflow','hidden');
			//$("#left_column .store_module .item_details .prices .price_line").hide().find('input').attr('disabled','disabled');
			/*
			//build select menu
			var opts = $('<select name="selector"><option value="">-- make your selection --</option></select>').change(function(){
				i = $(this).val();
				if(i){
					$(this).next().html($("#left_column .store_module .item_details .prices .price_line:eq(" + i + ") div.ui").html());
					$(this).next().find('input').removeAttr('disabled');
				}
				//order button
				$(".store_module .price_selector .submit").mousedown(function(){
					o = $(this).parents('.price_selector').find('.input');
					if(!o.val())
						o.val(1);
				});
			});
			*/
			var p;
			$("#left_column .store_module .item_details .prices .price_line").each(function(){
				p = $(this).find('span.new_price').html();
				r = $(this).children('div.price').find('span.ref').text();
				t = $(this).children('div.price').find('span.article').text();
				//opts.append($('<option value="' + $("#left_column .store_module .item_details .prices .price_line").index($(this)) + '">' + t + ' (' + r + ')</option>'));
			});
			$("#left_column .store_module .item_details .prices .price_line").css('display','none');
			//$("#left_column .store_module .item_details .prices").prepend($('<div class="price_selector"><span class="selector_ui"></span></div>')).find('.price_selector').prepend(opts);
			$("#left_column .store_module .item_details div.specs").append($('<div class="spec_item spec_item_"><div class="spec spec_line_75 spec_value"><label>Price:</label> <span class="value">' + p + '</span></div></div>'));
			$("#left_column .store_module .item_details div.more_info").append($('<div class="new_price"><h2>'+ p + '</h2></div>')); //  style="float:right;clear:both;display:block;height:30px;"
			//opts.trigger('change');
		}else{
			//order button
			$(".store_module .price_line .ui .submit").mousedown(function(){
				o = $(this).parents('.ui:eq(0)').find('input.input');
				if(!o.val())
					o.val(1);
			});
		}

		// move thumbnails to preview container
		$('#left_column .store_module .item_details div.preview').append($('.photoalbum_module'));
		//change album click
		$("#left_column .store_module .item_details .photoalbum_thumb a").click(function(e){
			e.preventDefault();
			u = $(this).attr('href').replace('index.php?','modules/photoalbums/index.php?json_photo_data=true&');//.replace(/&photoID=([0-9]+)/,'&photoID=0');
			$.getJSON(u,function(data){
				$("#left_column .store_module .item_details div.preview img:eq(0)").attr('src',data['photo']['path']);
				var id = 'popwinlink_' + uid();
				img[id] = new Image();
				img[id].onload = function(){
					img[id].onload = null;
					w = img[id].width;
					h = img[id].height;
					$("#left_column .store_module .item_details div.preview a:eq(0)").attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + img[id].src + "'," + w + "," + h + ");");
				}
				img[id].src = data['photo']['path'].replace('AlbumPreview.','');
			});
			return false;
		});

		//add category listing...
		if($("#left_column .store_module .item_details").length){
			h = self.location.href;
			c = s = '';
			if(h.indexOf('/shop/') > -1){
				f = h.match(/\/shop\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)/);
				b = f[1];
				x = f[2];
				c = f[3];
				s = f[5];
				i = f[8];
			}
			if(c || s){
				$.getJSON('/domains/theoldman.nl/js/get_shop_categories_agent.php',{categoryID:(s ? s : c),ID:i},function(data){
					for(i in data){
						$("#left_column .store_module .item_details div.photoalbum_thumbs").append('<span class="photoalbum_thumb"><a href="/index.php?module=shop&buttonID=' + b + '&categoryID=' + c + '&subcategoryID=' + s + '&articleID=' + i + '&shopID=' + x + '"><img src="' + data[i] + '" border="0" /></a></span>');
					}
				});
			}
		}
		$(".store_module div.listing div.thumb img,.store_module div.listing div.no_thumb span").each(function(){
			$(this).css({marginTop:72.5 - ($(this).outerHeight() / 2),display:'block'});
		});
	}

/*	-------------------------------------------
	REMOVE CLEAR FROM CATEGORY MENU
	----------------------------------------- */
	
	$('ul.shop_manufacturers a,ul.shop_categories a').removeClass('clear');

/*	-------------------------------------------
	HIDE BR BEFORE MODULES / KILL EMPTY ARTICLES
	----------------------------------------- */
	
	$(".module_contents").each(function(){
		if($(this).prev('br').length == 1){
			$(this).prev('br').remove();
		}
	});

	$(".article,.title").each(function(){
		if(!$.trim($(this).text()) && !$(this).find('img,object,embed,form,input,frame,.sIFR-replaced').length){
			$(this).remove();
		}
	});

/*	-------------------------------------------
	CHANGE POPUPS
	----------------------------------------- */

	var img = new Array();
	$(".article a").each(function(){
		i = 0;
			
		//change all onclick popups
		if($(this).attr('onclick')){
			i = $(this).attr('onclick').toString().indexOf("dow.open(this.href,");

			if(i){
				w = 640;
				h = 480;
				
				u = $(this).attr('href');
				e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
				
				if(e == 'png' || e == 'gif' || e == 'jpg'){
					var id = 'popwinlink_' + uid();
					$(this).attr('id',id);

					img[id] = new Image();
					img[id].onload = function(){
						img[id].onload = null;
						w = img[id].width;
						h = img[id].height;
	
						$("a#" + id).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");
					}
					img[id].src = u;
				}else{
					c = $(this).attr('onclick');
	
					h = c.substring(c.indexOf('height=') + 7);
					h = h.substring(0,h.indexOf(','));
	
					w = c.substring(c.indexOf('width=') + 6);
					w = w.substring(0,w.indexOf(','));
	
					$(this).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");				
				}
			}

		//change all movie files
		}else if($(this).attr('href') && $(this).attr('href').match(/.(flv|FLV)$/)){
			//get filename...
			u = $(this).attr('href').match(/(\/db\/.*.(flv|FLV)$)/)[1];
			$(this).addClass('popWindowLink').attr('href',"javascript:popWindow('/domains/theoldman.nl/video.php?file=" + u + "',320,260);");		
		}
	});

/*	-------------------------------------------
	MAKE SAME HEIGHT
	----------------------------------------- */
	
	make_same_height('.store_module div.listing div.article');

/*	-------------------------------------------
	RANDOM ARTICLE MODULE
	----------------------------------------- */
	
	if($(".random_article_module").length){
		make_same_height('.random_article_module .random_article');
		$(".random_article_module .random_article a.thumbnail").addClass('clear');
		$(".random_article_module .random_article a.thumbnail").find('img:eq(0)').wrap('<span class="thumb" />');
		$(".random_article_module .random_article span.thumb img").each(function(){
			$(this).css({marginTop:72.5 - ($(this).outerHeight() / 2),display:'block'});
			$(this).css('margin-left','auto');
			$(this).css('margin-right','auto');
		});
	}


/*	-------------------------------------------
	LAST ADDED MODULE
	----------------------------------------- */
	
	if($(".last_added_module").length){
		$(".last_added_module ol li a").addClass('clear');
		$(".last_added_module ol li a").find('img:eq(0)').wrap('<span class="thumb" />');
		$(".last_added_module ol li span.thumb img").each(function(){
			$(this).css({marginTop:72.5 - ($(this).outerHeight() / 2),display:'block'});
			$(this).css('margin-left','auto');
			$(this).css('margin-right','auto');
		});
	}

});

