$(document).ready(function(){
	$('#delimg').click(function(){
	 	$('input[type="file"]:last', $(this).parents('td:first') ).remove();
	 	return false;
	})
	$('#addimg').click(function(){
		$(this).parents('td:first').append('<input type="file" name="images[]" />');
		return false;
	})
	
	$('input[name="extra_params"]').click(function(){
		if( $(this).val() == 'yes' ) {
			$('#noextra').hide();
			$('#extra_params').show();
		} else {
			$('#noextra').show();
			$('#extra_params').hide();
		}
	})
	$('#add_extraparam').click(function(){
		$('#extra_params').append('<tr>'+
	                                  '<td>Параметър : </td>'+
	                                  '<td><input type="text" name="extraparam[]" style="width: 100px;"></td>'+
	                                  '<td>Наличност: </td>'+
	                                  '<td><input type="text" name="extraparam_av[]" style="width: 20px;"><a href="#" class="delete_param">изтрии</a></td>'+
	                                '</tr>');
		return false;
	})
	$('#order_prods').change(function(){
		document.location = currLocation + '&order='+$(this).val();
	})
	imagePreview();	
	$('.lightbox').lightBox();
	
	$('#show_inqform').click(function(){
		$('#inquire_table').fadeIn();
		return false;
	})
	
	$('#ownprods .delete').click(function(){
		var tr = $(this).parents('tr:first');
		var id = tr.get(0).id;
		tr.remove();
		$.getJSON('/deleteprod/?id='+id, {}, function(json){
//			console.log(json);
//			console.log(tr);
//			tr.remove();
		})
		return false;
	})
	$('.delete_img').click(function(){
		var imgId = $(this).get(0).rel;
		var prodId = $('input[name="id"]').val();
		$(this).parents('div:first').remove();
		$.getJSON('/delete-image/?id='+imgId+'&pid='+prodId, function(json){});
		return false;
	})
	$('.delete_param').click(function(){
		$(this).parents('tr:first').remove();
		return false;
	})
	$("#dialog_toecart").dialog({
		bgiframe: true,
		height: 140,
		modal: true,
		autoOpen: false
	});
	$("#dialog_available").dialog({
		bgiframe: true,
		height: 140,
		modal: true,
		autoOpen: false
	});
	$("#dialog_fillfields").dialog({
		bgiframe: true,
		height: 140,
		modal: true,
		autoOpen: false
	});
	$("#dialog_orderconfirm").dialog({
		bgiframe: true,
		height: 140,
		modal: true,
		autoOpen: false,
		buttons: {
			'Не': function() {
				$(this).dialog('close');
			},
			'Потвърждавам': function() {
				$('form#cartform').get(0).submit();
			}
		}

	});

	$('#add_tocart').click(function(){
		var url = '';
		switch(extraParams) {
			case 'no':
				url = '/addtocart/?pid='+prodId+'&quant='+$('#quantity').val();
				break;
			case 'yes': 
				url = '/addtocart/?pid='+prodId+'&quant='+$('#quantity').val()+'&param='+$('#params').val();
				break;
		}
		$.getJSON(url, function(data){
			if( data.success ) {
				$('#ecart_count').text( parseInt( $('#ecart_count').text() ) + 1 );
			}
			$('#dialog_toecart p').html(data.msg);
			$("#dialog_toecart").dialog('open');
		})
		return false;
	})
	$('input.quantity_input').change(function(){
		var parts = $(this).get(0).id.toString().split('-');
		var userId = parseInt( parts[1] );
		var prodIds = parts[2];
		var partsIds = prodIds.split('_');
		var pid = parseInt( partsIds[0] );
		var paramId = parseInt( partsIds[1] );
		var quant = parseInt( $(this).val() );
		var tr = $(this).parents('tr:first');
		var table = $(this).parents('table:first');
		
		var available = parseInt( $('.max_available', tr).val() );
		if( quant > available ) {
			quant = available;
			$(this).val(quant);
			$('#item_available').text( quant );
			$("#dialog_available").dialog('open');
		}
		$('.req_price', tr).text( parseFloat( quant * parseFloat( $('.actual_price', tr).text() ) ).toFixed(2) );
		var total = 0;
		$('tr', table).each(function(){
			if( $('.actual_price', this).text() ) {
				total += parseFloat( $('.actual_price', this).text() ) * parseInt( $('.quantity_input', this).val() );
			}
		})
		$('.total_price', table).text( total.toFixed(2) );
		$.getJSON('/addtocart/?pid='+pid+'&quant='+quant+'&param='+paramId, function(data){});
	})
	
	$('input[name="submitOrder"]').click(function(){
		$("#dialog_orderconfirm").dialog('open');
		return false;
	})
	
	$('a.preview').click(function(){ return false; })
	
	$('#promo').change(function(){
		$('.onpromo').toggle();
	});
	$('#sell_online').change(function(){
		if( $(this).val() == 'sellerurl' ) $("#sell_online_inp").show();
		else $("#sell_online_inp").hide();
		//return false;
	})
	$('#uploadprodfrm').submit(function(){
		var ret = true;
		$('.required', $(this)).each(function(i){
			if( $(this).val().length < 1 ) { ret = false; console.log( $(this).get(0).name ); }
		})
		$('.required_email', $(this)).each(function(i){
			if( !Validate.email( $(this).val() ) )  { ret = false; console.log( $(this).get(0).name ); }
		})
		var checkbox = false;
		$('.required_checkbox_gf', $(this)).each(function(i){
			if( $(this).get(0).checked ) checkbox = true;
		})
		if( !checkbox )  { ret = false; console.log( 'required_checkbox_gf' ); }
		checkbox = false;
		$('.required_checkbox_oc', $(this)).each(function(i){
			if( $(this).get(0).checked ) checkbox = true;
		})
		if( !checkbox ) { ret = false; console.log( 'required_checkbox_oc' ); }
		var radio = false;
		$('.required_radio_cat', $(this)).each(function(i){
			if( $(this).get(0).checked ) radio = true;
		})
		if( !radio )  { ret = false; console.log( 'required_radio_cat' ); }
		if( $('#extra_params_no').get(0).checked ) {
			if( parseInt( $('#available').val() ) <= 0 )  { ret = false; console.log( 'available' ); }
		}/* else if( $('#extra_params_yes').get(0).checked ) {
			
		}*/
		if( $('#promo').val() == 'yes' ) {
			if( parseDouble( $('#promo_price').val() ) <= 0 )  { ret = false; console.log( 'promo price' ); }
		}
		
		if( !ret ) {
			$("#dialog_fillfields").dialog('open');
			return false;
		}
	})
	
	$('#to_sellerurl').click(function(){
		window.open($(this).get(0).href, 'Сайт на търговец', 'height = 600, width = 800');
		return false;
	})
});

this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};
