// firebug degradation
/*if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i){
        window.console[names[i]] = function() {}
	}
}*/

$(document).ready(function() {
	$("#stars-wrapper2").stars({
	    inputType: "select",
	    oneVoteOnly: true
	});

	// Retrieve instance
	/*var instance = $("#stars-wrapper2").data("stars");
	// Read options
	var currID    = instance.options.checked; // Get current ID
	var currValue = instance.options.value; // Get current Value
	var currTitle = instance.options.title; // Get current Title
	var cancValue = instance.options.cancelValue; // Get Cancel value
	// Remove Cancel button
	instance.$cancel.remove();
	// Append new, static star - don't ask why ;-)
	var $newStar = instance.$stars.eq(0).clone()
		.removeClass(instance.options.starOnClass).css({cursor: "default"})
		.insertAfter(instance.$stars.eq(instance.options.items-1));*/
	
/**************************** SLIDER ****************************/
	if($('#s3slider').length){
		$('#s3slider').click(function(){
	   		//$('location').attr('href', base_url+'create/');
	   		location.href = base_url+'create/';
	   	}).hover(function(){
	   		$(this).css('cursor','pointer');
	   	}).s3Slider({
	    	timeOut: 4000
	   	});
	}

/**************************** INFINITE SCROLLER ****************************/
	/*if($('#products').length && $('#pagers').length){
		var product_page = 0;
		var per_page = 36;
		var stop_reloading = false;
		var busy_reloading = false;
		$(window).scroll(function(){
	        if (!stop_reloading && !busy_reloading && $(window).scrollTop()+$(window).height() >= $('#pagers').offset().top){
	        	product_page++;
	        	busy_reloading = true;
	        	$.get(location.href+(product_page*per_page)+'/', function(data){
	        		if(!$(data).find('#products').length){
	        			stop_reloading = true;  
	        		}
	        		$('#products').append($(data).find('#products'));
	        		busy_reloading = false;
	        	});
	        }
		});
	}*/
	
/**************************** ANGEBOTE / PRICE_CUT SUBSCRIBE ****************************/
	$('#submit_mail').click(function(){
		var data = $('#subscription').serialize();
		data += "&ajax=true";
		$.post(base_url+"angebote/subscribe/", data,
			function(data){
		    	if(data.status === true){
		    		$('#subscribe').html('Du wirst ab sofort kostenlos &uuml;ber neue Angebote informiert.');
		    	} else {
		    		$('#subscribe').html('Leider konnte Dein Mail-Auftrag nicht erstellt werden.');
		    	}
  			}, "json");
		return false;
	});

/**************************** PRODUCT ****************************/
	if($('#action_list').length){
		//$('#subscribe').css('visibility','hidden');
		$('#subscribe').toggle();
		$('#preisalarm').click(function(){
			$('#subscribe').toggle();
		});
		$('#action_list').find('span').hover(
			function(){
				$(this).find('img').css('width','47px').css('height','47px');
			},
			function(){
				$(this).find('img').css('width','48px').css('height','48px');
		});
	}

/**************************** COLOR ****************************/
var color_names = new Array();
color_names['red'] = 'rot';
color_names['orange'] = 'orange';
color_names['yellow'] = 'gelb';
color_names['green'] = 'gr&uuml;n';
color_names['blue'] = 'blau';
color_names['violet'] = 'violett';
color_names['brown'] = 'braun';
color_names['black'] = 'schwarz';
color_names['grey'] = 'grau';
color_names['white'] = 'wei&szlig;';
$('#colors li').hover(
function(){
	$(this).css('cursor', 'pointer');
	$('#color_name').html(color_names[$(this).attr('id')]);
},
function(){
	$('#color_name').html('');
}
).click(function(){
	if($('#color').attr('value') === $(this).attr('id')){
		$('#color').attr('value', '');
		$(this).css('border', '1px dotted #999999');
	} else {
		$('#colors li').css('border', '1px dotted #999999');
		$('#color').attr('value', $(this).attr('id'));
		$(this).css('border', '2px solid #ffffff');
	}
});

/**************************** LOGO ****************************/
	/*$('#logo').hover(
		function(){
			$(this).css('cursor', 'pointer');
			$(this).animate({
					top: '-10px'
				}, 800, 'swing', function() {
				});
		},
		function(){
		$(this).css('cursor', 'default');
			$(this).animate({
					top: '-100px'
				}, 800, 'swing', function() {
				});
		}

	);*/
/**************************** PRODUCT ****************************/
if ($('#product_image').length && $('#product_link').length) {
	$("#product_image").click(function(){
		window.open($('#product_link').attr('href'));
	}).hover(function(){
		$(this).css('cursor','pointer');
	});
}
/**************************** ZOOM ****************************/
/*var options = {
    zoomWidth: 300,
    zoomHeight: 350,
    xOffset: 10,
    yOffset: 0,
    lens:false,
    title:true,
    showPreload: false
};
$(".zoom").jqzoom(options);*/
var options = {imgSource:'rel'};
$(".zoom:has(img)").bezoom(options);

var options = {imgSource:'data'};
$("#product_image").bezoom(options);

/**************************** INPUT /  PASSWORDS ****************************/
/*var html = '<input id="pw-clear" type="text" name="pw" value="Passwort" />';
var name = $('#password').attr('name');
var value = $('#password').attr('value');
var id = $('#password').attr('id');

$('#password').after(html).remove();
$('#pw-clear').focus(function(){
	var html = '<input type="password" name="'+name+'" value="'+value+'" id="'+id+'"/>';
	$(this).after(html).remove().focus();
	//$('input:password').dPassword();
	$('#password').dPassword();
});
*/
$('#username').attr('value', 'Benutzername');
$('#username').focus(function(){
	if($(this).attr('value') === 'Benutzername'){
		$(this).attr('value', '');
	}
}).blur(function(){
	if($(this).attr('value') === ''){
		$(this).attr('value', 'Benutzername');
	}
});

$('#password').attr('value', 'Passwort');
$('#password').focus(function(){
	if($(this).attr('value') === 'Passwort'){
		$(this).attr('value', '');
	}
}).blur(function(){
	if($(this).attr('value') === ''){
		$(this).attr('value', 'Passwort');
	}
});

/*****************	QUICKLIST  *********************************************/
// create quicklist dom
$('.ql_container').html('	<div class="ql_top"></div>'+
'	<div id="quicklist">Hier kanst Du Deine Lieblingsartikel zwischenspeichern.</div>'+
'	<div class="ql_info">'+
'		<div id="quicklist_weitere"></div>'+
'		<div id="quicklist_show"></div>'+
'	</div>'+
'	<div class="ql_bottom"></div>');

//Slide up and down on click
$(".ql_bottom").mouseover(function(){$(this).css('cursor', 'pointer')}).click(function(){
	//console.log('clicked');
	//$(this).next("#quicklist").slideToggle("slow");
	$("#quicklist").slideToggle("slow");
});



// entfernen buttons in in/show_quicklist/ anzeigen
$('#quicklist_main a').each(function(i){
	showQLRemover($(this));
/*	$(this).mouseleave(function(){
		$(this).find('.adder').remove();
	});
	 $(this).mouseenter(function(){
	 	console.log('enter');
	 	$(this).append('<span class="adder" style="margin-left:-10px;color:#ffffff;background-color:#333333;">&nbsp;-&nbsp;</span>');
	 	var href  = $(this).attr('href');
	 $(this).find('.adder').each(function(k){
	 	$(this).mouseover(function(){$(this).css('cursor', 'pointer')}).click(function(event){
	     	event.preventDefault();
	     	that = $(this);
			that.html('<img src="'+base_url+'bttns/loading_flat.gif">');
			$.post(base_url+'in/rem/', { slug: href },
			  function(responseData){
			  	if(responseData.error === false){
					//that.html('gespeichert!').attr('class', 'remembered');
					that.html('').attr('class','');
					that.mouseover(function(){that.css('cursor', '');});
					remFromQuickList(href);
				} else {
					// TODO
					console.log('Fehler');
				}

			  }, "json");
	 	});
	 });
	});*/
});


// merken buttons auf produktlisten anzeigen
$('#products a').each(function(i){
	$(this).mouseleave(function(){
		$(this).find('.adder').remove();
	});
    $(this).mouseenter(function(){
	var pos = $(this).position();

	var marginLeft = $(this).find('img').css('margin-left');
	marginLeft = marginLeft.substring(0, marginLeft.length-2)-0;
	var marginTop = $(this).find('img').css('margin-top');
	marginTop = marginTop.substring(0, marginTop.length-2)-0;

	var y = Math.ceil(pos.top-0)-13+marginTop;
	var x = Math.ceil(pos.left-0)+$(this).find('img').width()-13+marginLeft;

    $(this).append('<span class="adder" style="position:absolute;left:'+x+'px;top:'+y+'px;color:#ffffff;background-color:#333333;">&nbsp;+&nbsp;</span>');
 	var href  = $(this).attr('href');
	 $(this).find('.adder').each(function(k){
	 	$(this).mouseover(function(){$(this).css('cursor', 'pointer')}).click(function(event){
	     	event.preventDefault();
	     	that = $(this);
			that.html('<img src="'+base_url+'bttns/loading_flat.gif">');

			$.post(base_url+'in/add/', { slug: href },
			  function(responseData){
			  	if(responseData.error === false){
					//that.html('gespeichert!').attr('class', 'remembered');
					that.html('').attr('class','');
					that.mouseover(function(){that.css('cursor', '');});
					addToQuickList(responseData);
				} else {
					// TODO
					//console.log('Fehler');
				}

			  }, "json");
	 	});
	 });
	});

});




// showing products in quicklist
$('#quicklist').each(function(i){
	$.postJSON(base_url+'in/get_quicklist/', {}, function(responseData){
		if(responseData.empty === false){
	  		//console.log('not empty');
    		for(property in responseData.items) {
				img_small = responseData.items[property].img_small;
	  			addToQuickList(responseData.items[property]);
	  			//$('#quicklist').prepend('<img src="'+img_small+'">');
	  		}
	  	} else {
	  		//TODO
	  		//console.log('empty');
	  	}
	});
});

// adding to quicklist
$('.remember').mouseover(function(){$(this).css('cursor', 'pointer')}).click(function(event){
	//event.preventDefault();
	that = $(this);
	that.html('<img src="'+base_url+'bttns/loading_flat.gif">');
	$.post(base_url+'in/add/', { pid: $(this).attr('id') },
	  function(responseData){
	  	if(responseData.error === false){
			that.html('gespeichert!').attr('class', 'remembered');
			that.mouseover(function(){that.css('cursor', '');});
			addToQuickList(responseData);
		} else {
			// TODO
			//console.log('Fehler');
		}

	  }, "json");
});

/************************ FEEDBACK **********************************************/

var feedbackContent =
'<div style="width:550px;">Hilf&apos; uns doch ModeSuche noch besser zu machen! Wir freuen uns auf dein <b>Feedback</b>.'+
'<div id="typeSelector"><b>W&auml;hle hier den Typ Deiner Nachricht:</b> <span>Idee</span> // <span>Frage</span> // <span>Problem</span></div>'+
'<form id="feedback_form" action="<?=base_url()?>feedback/" method="post">'+
'  <label for="nachricht">Deine Nachricht</label><textarea class="big wide" name="nachricht" rows="4"></textarea>'+
'  <label for="adresse">Deine Mail-Adresse</label><input class="text_field big wide" type="text" name="adresse" value="" />'+
'  <label for="name">Dein Name</label><input class="text_field big wide" type="text" name="name" value="" />'+
'  <input class="big_button"  type="submit" name="submit" id="submit" value="abschicken"/>'+
'  <input type="hidden" name="typ" id="typ" value="idee"/>'+
'</form></div>';
	 $('#feedback').click(function(e){
        e.preventDefault();

		// JS im iframe
		$(document).bind('reveal.facebox', function() {
			//$(document).unbind('reveal.facebox');
			//console.log($('#typeSelector span').size());
			$('#typeSelector span').mouseover(function(){
				$(this).css('cursor','pointer');
			});

			$('#typeSelector span:first').css('background', 'transparent url('+base_url+'css/tip-pimped.gif) no-repeat -2px -3px');
			$('#typeSelector span').click(function(){
				$('#typeSelector span').css('background', '');
				$(this).css('background', 'transparent url('+base_url+'css/tip-pimped.gif) no-repeat -2px -3px');

				$('#typ').attr('value', $(this).html());
			});
			$('#submit').click(function(ev){
		        ev.preventDefault();
		        //console.log('sending');
				var values = $("#feedback_form").serialize();
				$.ajax({
					type: "GET",
					url: base_url+'feedback_remote/',
					cache:false,
					data: values,
					dataType:'jsonp',
					success: function(resp) {
						if(resp === 'kk'){
							$('#facebox .content').html('<h1>Deine Nachricht wurde &uuml;bermittelt. Danke!</h1>Falls Du eine Mail-Adresse angegeben hast werden wir uns melden.')
						}
					}       // end success function
				});     // end ajax call
			}); // end on submit

			/*$.ajax({
				dataType: 'jsonp',
				jsonp: 'jsonp_callback',
				url: 'http://localhost/devtips_jsonp/jsonp.php',
				success: function (data) {
					alert(data.Paul);
				},
			});*/

		}); // end JS im iframe

		var iframe = '<div style="width:550px; margin:0px;padding:0px;"><iframe width="550" height="500" src="'+base_url+'/feedback_remote/"></iframe></div>';
		jQuery.facebox(iframe);



		//jQuery.facebox({ ajax: 'http://google.de/' })
		/*jQuery.facebox(function($) {
      		jQuery.get('http://google.de/', function(data) { jQuery.facebox(data) })
	    })*/

     });
//	$('a.iframe').facebox()

});


/**************************** MORE QUICKLIST ****************************/
function showQLRemover(item){
	item.unbind('mouseenter');
	item.find('.adder').unbind('click');
	item.mouseleave(function(){
		item.find('.adder').remove();
	});
	item.mouseenter(function(){
		//console.log('enter '+$(this).attr('href'));
		var pos = $(this).position();

		var y = Math.ceil(pos.top-0)-10;
		var x = Math.ceil(pos.left-0)+$(this).find('img').width()-10;
	    item.append('<span class="adder" style="position:absolute;left:'+x+'px;top:'+y+'px;color:#ffffff;background-color:#333333;">&nbsp;-&nbsp;</span>');
	 	//item.append('<span class="adder" style="margin-left:-10px;color:#ffffff;background-color:#333333;">&nbsp;-&nbsp;</span>');
	 	var href  = item.attr('href');
		item.find('.adder').each(function(k){
		 	$(this).mouseover(function(){item.css('cursor', 'pointer')}).click(function(event){
		     	event.preventDefault();
				$(this).html('<img src="'+base_url+'bttns/loading_flat.gif">');
				var that = $(this);
				$.postJSON(base_url+'in/rem/', { slug: href }, function(responseData){
					that.html('').attr('class','');
					that.mouseover(function(){item.css('cursor', '');});

					// alles entfernen und resetten
					$('#quicklist').html('');
					$('#quicklist_show').html('');
					$('#quicklist_weitere').html('');
					remFromQuickList(href);
					quicklistCount = 0;

			  		// falls noch items in quicklist sind => wieder füllen
			  		if(responseData.empty === false){
			    		for(property in responseData.items) {
							img_small = responseData.items[property].img_small;
				  			addToQuickList(responseData.items[property]);
				  		}
			  		}
				});
			});
		});
	});
}

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};
quicklistCount = 0;
quicklistSize = 3;
function addToQuickList(responseData){
	quicklistCount++;
	var quicklist = $('#quicklist');
	if(quicklist.find('a').size() === 0 ){
		// text entfernen um produkte zu speichern
		quicklist.html('');
		$('#quicklist_show').html('<a href="'+base_url+'in/show_quicklist/">alle anzeigen</a>');
	} else {
		// doppelte entfernen um neues vorne anzuhängen
		quicklist.find('a').each(function(i){
			link = base_url+'product/'+responseData.slug+'/';
			if($(this).attr('href') === link){
				$(this).remove();
				quicklistCount--;
			}
		});
	}
	//quicklist.prepend('<a href="'+base_url+'product/'+responseData.slug+'/"><img src="'+responseData.img_small+'"></a>');
	var newElem = $('<a href="'+base_url+'product/'+responseData.slug+'/"><img src="'+responseData.img_small+'"></a>');
	newElem.prependTo(quicklist);
	while(quicklist.find('a').size() > quicklistSize ){
		// älteste produkt nicht mehr anzeigen
		quicklist.find('a:last').remove();
		$('#quicklist_weitere').html('... und '+(quicklistCount-quicklistSize)+' Weitere.')
	}
	//console.log(responseData.pid);
	//console.log(responseData.count);

	showQLRemover(newElem);

}

function remFromQuickList(slug){
	//console.log('remove From Quicklist '+slug)
	var quicklist = $('#quicklist');
	quicklistCount--;

	// produkt aus quicklist entfernen
	// wird nicht mehr gebraucht, da komplette quicklist refresht wird
	/*quicklist.find('a').each(function(i){
		//link = base_url+'product/'+slug+'/';
		if($(this).attr('href') === slug){
			$(this).remove();
		}
	});*/

	$('#quicklist_main a').each(function(i){
		//link = base_url+'product/'+slug+'/';
		if($(this).attr('href') === slug){
			$(this).remove();
		}
	});

	// TODO Produkte in quicklist wieder auffüllen, falls eins gelöscht wurde, da sichtbar war
	// TODO "weitere"-Anzeige anpassen

	if(quicklist.find('a').size() === 0 ){
		// text entfernen um produkte zu speichern
		quicklist.html('Hier kanst Du Deine Lieblingsartikel zwischenspeichern.');
		$('#quicklist_show').html('');
		$('#quicklist_weitere').html('');
	}
}

