if( !window.console ) {
	window.console 		 = function(){};
	window.console.log   = function(c) { alert(c); };
	window.console.info  = function(c) { alert(c); };
	window.console.dir   = function(c) { alert(c); };
	window.console.error = function(c) { alert(c); }; 
}

JF = function(){
	var instance = this;
	
	this.user = {};
	
	this.isInfoBox = false;
	
	this.info = false;

	
	this.api = base_url;
	
	$(document).ready(function(){
		$(window).scroll(function(){
			var scrollTop = $(this).scrollTop();
			instance.InfoSetTop( scrollTop );
		});
		
		if( !$.browser.msie ) {
			$('.labpasshide').css({ display : 'inline' });
		}
	
		$('#inesita2').mouseover(function(){
			$(this).effect("pulsate", { times: 1 }, 200);
		});
		$('#inesitadev').mouseover(function(){
			$(this).effect("pulsate", { times: 1 }, 200);
		});
		
/*		
		$("#colors ul li").tooltip({ 
		    track: true, 
		    delay: 0, 
		    showURL: false, 
		    opacity: 0.9, 
		    fixPNG: true, 
		    //showBody: " - ", 
		    top: -15, 
		    left: 5,
		    bodyHandler: function(e) { 
		        return "aaaaaaaaa"; 
		    } 
		});
*/
		var colors = $("#colors ul li");
		var elem = {};
		for( var i = 0, len = colors.length; i < len; i++ ) {
			elem = $( colors[i] );
			elem.tooltip({ 
			    track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 0.9, 
			    fixPNG: true, 
			    //showBody: " - ", 
			    top: -20, 
			    left: 15,
			    bodyHandler: function(el) {
			    	return function(){
			        	return '<span style="color:#BF474F;">' + $( el[0] ).find( 'span' )[0].innerHTML + '</span>'; 
			    	}
			    }(elem)
			});

		}
		
		$( '#emailField' ).keypress(function(e){
			if( e.keyCode == 13 ) {
				if( $( '#passwordField' ).val() != '' )
					instance.loginAction();
			}
		});
		
		$( '#passwordField' ).keypress(function(e){
			//console.log( e.keyCode );
			if( e.keyCode == 13 ) {
				instance.loginAction();
			}
		});
	});
	
	this.comms = {};
};

JF.prototype.confrim = function( url, txt ){
	
	var txt = txt || 'Usunac wybrany element';
	
    if (confirm(txt) == true) {
    	window.location.href = url;
    } else {
    	return false;
    }
}

JF.prototype.hideElement = function( elem ) {

	window.setTimeout(function(){

		$( '#'+elem ).animate({
			opacity : 0,
			width: '500px'
		},
		500,
		'linear',
		function(){ 
			$( '#'+elem ).animate({
				height : '0px'
			});
		});

	}, 3000 );

};

JF.prototype.checkCommentForm = function( elem, form ) {
	
	if( /^[^\ ].*/.test( $( '#'+elem )[0].value ) ) {
		$( '#'+form ).submit();
		$( '#'+elem ).css( { border: '1px solid green' } );
	} else {
		var handler;
		$( '#'+elem ).click( handler = function(){
			$( '#'+elem )[0].value = '';
			$( '#'+elem ).unbind( 'click', handler );
		} );
		$( '#'+elem ).css( { border: '1px solid red' } );
	}
};

JF.prototype.checkRegForm = function() {
	var instance = this;

	var commMng = function( action, elem, comm, valign ) {
	
		var valign = valign || 'right';
	
		var bounds = elem[0].getBoundingClientRect();
		
		if( action == 'add' ) {
			if( !instance.comms[elem.attr( 'id' )] ) {
				instance.comms[elem.attr( 'id' )] = $( '<div></div>' ).attr({
					className : 'comm'
				}).text( comm );

				if( valign == 'right' ) {
					instance.comms[elem.attr( 'id' )].css({
						left: parseInt( bounds.right + 10, 10 ) + 'px',
						top: parseInt( bounds.top + $( window ).scrollTop() + 4, 10 ) + 'px'
					});
				} else if ( 'top' ) {
					instance.comms[elem.attr( 'id' )].css({
						left: parseInt( bounds.left, 10 ) + 'px',
						top: parseInt( bounds.top + $( window ).scrollTop() - 20, 10 ) + 'px'
					});
				}
		
				$(document.body).append( instance.comms[elem.attr( 'id' )] );
			}
		} else {

			if( instance.comms[elem.attr( 'id' )] ) {
				try{
					$(document.body)[0].removeChild( instance.comms[elem.attr( 'id' )][0] );
					instance.comms[elem.attr( 'id' )] = false;
				}catch(e){}
			}
		}
		
	};
	
	var email = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
	var text = /[^\ ](.*)/;

	var elems = $( 'form#reg input, form#reg select' );
	
	var erors = 0;
	
	var attr, elem;
	for( var i = 0, len = elems.length; i < len; i ++ ) {

		elem = $( elems[i] );
		attr =  elem.attr( 'regexp' );

		if( attr == 'text' ) {
			if( text.test( elem.val() ) ) {
				commMng( 'del', elem );
			} else {
				commMng( 'add', elem, 'Pole nie jest uzupełnione' );
				erors = 1;
			}
		} else if ( attr == 'selected' ) {
			if( elem[0].options[elem[0].selectedIndex].value == '' ) {
				commMng( 'add', elem, 'Województwo nie jest zaznaczone' );
				erors = 1;
			} else {
				commMng( 'del', elem );
			}
		} else if( attr == 'checked' ) {
			if( elem[0].checked ) {
				commMng( 'del', elem );
			} else {
				commMng( 'add', elem, 'Oświadczenie o znajomości regulaminu musi zostać zaznaczone', 'top' );
				erors = 1;
			}
		} else if ( attr == 'email' ) {
			if( email.test( elem.val() ) ) {
				commMng( 'del', elem );
			} else {
				commMng( 'add', elem, 'To nie jest poprawny adres e-mail' );
				erors = 1;
			}
		}
	}

	return ( erors ) ? false : true;
};

JF.prototype.login = function() {
	var instance = this;
	
	var loginBtn = $('#login');
	
	$(document).ready(function(){
		loginBtn.click( function(){
			instance.loginAction();
		} );
	});
};

JF.prototype.loginAction = function(){
	var instance = this;
	
	var errors = 2;
	
	var email = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
	var text = /[^\ ](.*)/;
	
	var userCont = $('#user');
	var emailField = $('#emailField');
	var passwordField = $('#passwordField');

	if( !email.test( emailField.val() ) ) {
		emailField.css({
			background : '#FFAFAF'
		});
		errors++;
	} else {
		emailField.css({
			background : 'white'
		});
		errors--;
	}
	
	if( !text.test( passwordField.val() ) ) {
		passwordField.css({
			background : '#FFAFAF'
		});
		errors++;
	} else {
		passwordField.css({
			background : 'white'
		});
		errors--;
	}
	
	if( errors == 0 ) {
		var layer = $('<div></div>');
		layer.css({
			position: 'absolute',
			top: '4px',
			left: '87px',
			opacity: 0,
			background: '#fff',
			width: '250px',
			height: '94px'
		});				
		userCont.append( layer );
		
		layer.animate({
			opacity : 0.9
		});
		
		instance.Info('Trwa logowanie...');
	
		$.post( this.api + 'index/login', {
			email : emailField.val(),
			password : passwordField.val()
		}, function( response ) {	
			
			if( response.result ) {
				instance.InfoDestroy();
				instance.Info('Logowanie udane ;)',2000);

				instance.user.info = response.info;
				
				layer.animate({
					opacity : 1
				}, 200, null, function(){
					var over = userCont.find( '.over' );						
					over.empty();
					over.append(
						'<div class="logged">'+
							'<div class="ls">'+
								'<b>' + instance.user.info.email + '</b><br /><br />'+
								 '- <a href="' + base_url + 'index/account">Moje konto</a><br />'+
								 '- <a href="' + base_url + 'index/account/sel/1">Historia zakupów</a><br />'+
								 '- <a href="' + base_url + 'index/logout">Wyloguj się</a><br />'+
							'</div>'+
							'<div class="rs">'+
								'<div class="basket"></div>'+
								'<div class="basketInfo"><a href="' + base_url + 'basket">Produktów w koszyku: (<span id="count" class="count">' + response.basketCount + '</span>)</a></div>'+
							'</div>'+
						'</div>'
					);
			
					layer.animate({
						opacity: 0
					}, 500, null, function(){
						layer.remove();
					});
				});
				
				
			} else {
				instance.InfoDestroy();
				instance.Info(';(',2000);
				layer.html( '<div class="loginError">Nieprawidłowy login lub hasło</div>' );
				window.setTimeout(function(){
					layer.animate({
						left: '67px'
					}, 100, null, function(){
						layer.animate({
							left: '500px'
						}, 200, null, function(){
							layer.remove();
						});
					});
				}, 1500);
			}

		},
			'json'
		);
	} else {
		this.Info('Musisz podać poprawny e-mail i hasło',5000);
	}
};

JF.prototype.addToBasket = function( id ) {
	var instance = this;
	
	this.InfoDestroy();
	
	var addBtn = $('#basketadd');
	
	var adding = false;
	
	addBtn.hover(function(){
		addBtn.animate({		
			marginLeft : '10px'
		},100).css({
			color : '#3F0000'
		});
	},function(){
		addBtn.animate({		
			marginLeft : '0px'
		},100).css({
			color : '#C40100'
		});
	}).click(function(){
		if( !instance.user.info ) {
			instance.LoginForm();
			$('html').animate({scrollTop:0}, 'slow', null, function(){
				instance.Info('Musisz się zalogować', 2000);
				$('#user').find( '.over' ).effect("highlight", null, 3000);
			});
		} else {
			if( adding ) return true;
			
			adding = true;
		
			addBtn.animate({
				opacity : 0
			}, 300, null, function(){
				addBtn.css({ display : 'none' });
			});
			instance.Info( 'Dodaje do koszyka' );
			
			$.post( instance.api + 'basket/add', {
				id : id
			},function( response ){
				adding = false;
				
				
				if( response.result && response.result.code == -1 ) {
					instance.LoginForm();
					instance.InfoDestroy();
					$('html').animate({scrollTop:0}, 'slow', null, function(){
						instance.Info('Musisz się zalogować', 2000);
						$('#user').find( '.over' ).effect("highlight");
						addBtn.css({ display : 'block', opacity: 1 });
					});
				} else if( response.result && response.result.code == -2 ) {
					instance.InfoDestroy();
					instance.Info('Ops... błąd wewnetrzny -2, spróbuj za chwile', 3000);
					window.setTimeout(function(){
						addBtn.css({ display : 'block', opacity: 1 });
					}, 500 );
				} else if( response.result && response.result.code == -3 ) {
					instance.InfoDestroy();
					instance.Info('Wybrany produkt jest już sprzedany', 3000);
				} else if( response.result && response.result.code == -4 ) {
					instance.InfoDestroy();
					instance.Info('Produkt dostępny <u>tylko</u> w komplecie', 3000);
				} else if( response.result && response.result.code == -5 ) {
					instance.InfoDestroy();
					instance.Info('Produkt znajduje się w innym koszyku', 3000);
				} else if( response.result && response.result.code == 500 ) {
					instance.InfoDestroy();
					instance.Info('Ops... błąd wewnetrzny 500, spróbuj za chwile', 3000);
					window.setTimeout(function(){
						addBtn.css({ display : 'block', opacity: 1 });
					}, 500 );
				} else if( response.result && response.result.code == -6 ) {
					instance.InfoDestroy();
					instance.Info('Ops... błąd wewnętrzny -6', 3000);
					/**
					 * #TODO alert do admina
					 */
				} else if( response.result && response.result.code == 0 ) {
					var count = $('#user').find( '#count' );
					
					var cnt = parseInt( parseInt( count[0].innerHTML, 10 ) + 1, 10 );
					count[0].innerHTML = cnt;
					
					instance.InfoDestroy();
					instance.Info('Produkt dodany do koszyka', 2000);
				}
			},'json');
			
			
		}
	});

};

JF.prototype.LoginForm = function() {
	var userCont = $( '#user' );
	var over = userCont.find( '.over' );						
	over.empty();
	over.append(
		'<label>'+
			'Email: <input id="emailField" type="text" name="email" />'+
		'</label>'+
		'<label>'+
			'Hasło: <input id="passwordField" type="password" name="password" />'+
		'</label>'+
		'<div class="lother"><a href="' + base_url + 'index/register">rejestracja</a> | <a href="' + base_url + 'index/remind">przypomnij hasło</a></div><div class="linfo"><a id="login" href="javascript:void(0);">Zaloguj</a></div>'+
		'<script type="text/javascript">'+
			'$$JF.login();'+
		'</script>'
	);
};

JF.prototype.Info = function( msg, autoDestroy, width ) {
	var instance = this;
	
	this.InfoDestroy();

	this.isInfoBox = true;

	var autoDestroy = autoDestroy || false; 
	
	var width = width || 200; 

	this.info = $('<div id="boxInfo" class="info"><div class="l"></div><div class="c"><div class="txt">' + msg + '</div></div><div class="r"></div></div>');
	this.info.css({
		top : $(window).scrollTop()
	});

	$(document.body).append( this.info );
	
	if( autoDestroy ) {
		window.setTimeout( function(){
			instance.InfoDestroy();
		}, autoDestroy );
	}
	
	var width  = this.info.width();
	var bounds = this.info[0].getBoundingClientRect();
	var body   = $('body').innerWidth();

	var sum = parseInt( width + bounds.left, 10 );
	
	if( sum >= body ) {
		this.info.css({
			left : parseInt( bounds.left - 60, 10 ) + 'px'
		});
	}
};

JF.prototype.InfoDestroy = function() {
	if( this.info ) {
		this.info.remove();
		this.info = false;
		this.isInfoBox = false;
	}
}

JF.prototype.InfoSetTop = function( val ) {
	if( this.isInfoBox ) {
		this.info.css({
			top : val
		});
	}
};

JF.prototype.setOpt = function() {
	var instance = this;
	
	$(document).ready(function(){
		
		var inputs = $( '.basketList' ).find( 'input' );
		
		var _action = function( type ) {
			if( type == 'zaz' ) {
				inputs.attr({ checked : 'checked' });
			} else if( type == 'odz' ) {
				inputs.attr({ checked : '' });
			} else if( type == 'del' ) {
				var cnt = 0;
				for( var i = 0, len = inputs.length; i < len; i++ ) {
					if( inputs[i].checked ) {
						if( !ids ) {
							var ids = inputs[i].name.split('_')[1];
						} else {
							ids += ',' + inputs[i].name.split('_')[1];
						}
						cnt++;
					}
				}
				if( cnt == 0 ) {
					instance.Info( 'Nie zaznaczono żadnego produktu', 3000 );
				} else {
					if (confirm('Usunąć wybrane produkty?') == true) {
						window.location.href = instance.api + 'basket/remove/items/' + ids;
					}
				}
			}
		}
		
		$('#opttools').find('span').click(function(e){
			_action( $( e.originalTarget ).attr('opt') );
		});
		
		$('#opttools2').find('span').click(function(e){
			_action( $( e.originalTarget ).attr('opt') );
		})
	
	});
};

JF.prototype.changeAttr = function( elem, txt ) {
	var elem2 = document.getElementById( elem );
	if( elem2.getAttribute( 'type' ) == 'password' ) {
		$( '#' + txt ).find( 'span' )[0].innerHTML = 'ukryj hasło';
		elem2.setAttribute( 'type', 'text' );
	} else {
		$( '#' + txt ).find( 'span' )[0].innerHTML = 'pokaż hasło';
		elem2.setAttribute( 'type', 'password' );
	}
};

$$JF = new JF();
