var minContentWidth = 1300;

/********** create jQuery shortcut ***************/
if (jQuery && typeof(J) == 'undefined') {
	J = jQuery;
}


/********** BIZPLACE namaspace **************/

if (!bizplace) {
	// create bizplace namespace
	var bizplace = {};
	// current address 
	bizplace.currentAddress = '';
	//in config tree group Index
	bizplace.groupIndex = 0;
	//in config tree tab Index
	bizplace.tabIndex = 0;
	//in config tree fieldset Index
	bizplace.fieldsetIndex = 0;
	
	bizplace.initialize = function(callback) {
		bizplace.JSON({
			// pobierz config
			config: {action: 'config'},
			// pobierz drzewo kategorii - zakladki i podkategorie dla wybranej grupy klientow
			tree: {action: 'tree', level: 0, range: 4},
			// pobierz koszyk
			cart: {action: 'cartget'},
			// pobierz plany z koszyka
			cartplans: {action: 'cartplans'},
			// zalogowany uzytkownik
			clientdata: {action: 'clientdataget'}
		}, function(data) {
			
			// config
			if (typeof data.config == 'object') {
				/*for (var i = 0; i < data.config.lang_list.length; i++) {
					data.config.lang_list[data.config.lang_list[i].id] = data.config.lang_list[i];
				}*/
				bizplace.config = data.config;
			}
			
			// drzewo kategorii
			if (typeof data.tree == 'object') {
				bizplace.tree = data.tree;
			}

				// plany do koszyka
			if (typeof data.cartplans == 'object') {
				// zapamietaj plany
				if (!bizplace.plans)
					bizplace.plans = {};
				if (data.cartplans.length) {
					for (var j = 0; j < data.cartplans.length; j++) {
						bizplace.plans[data.cartplans[j].id] = data.cartplans[j];
					}
				} else {
					for (var j in data.cartplans) {
						bizplace.plans[data.cartplans[j].id] = data.cartplans[j];
					}
				}
			}
			// koszyk
			if (typeof data.cart == 'object') {
				bizplace.cartUpdate(data.cart);
			}
			
			// dane usera
			if (typeof data.clientdata == 'object')
				bizplace.clientdata = data.clientdata;

			
			if (typeof(callback) == 'function')
				callback('stepsPlans');
		
			
			/********** deep linking with jQuery Address **************/
			if (jQuery && jQuery.address) {
				J.address.change(bizplace.process);
			}
			
			//ustalenie pozycji social
//			whereToPutSocial();
			//sprawdzamy co jest w adresie i reagujemy
			bizplace.process();
		});
	}
}


/********* Content Place Functions*****************/
//function stepsOnResize(){
//	if(J('.stepsMenu').length > 0){		//blokada dzialania na podstronach
//		whereToPutSocial();
//		resizeMenu();
//		resizeTab();
//	}
//}

//function whereToPutSocial(){
	/*if(J('.stepsMenu').length > 0){		//blokada dzialania na podstronach
		if(parseInt(J('#contentHolder').width()) < minContentWidth )
			J('#societyContainer').addClass('smallVersion').css('margin-left','0');
		else
			J('#societyContainer').removeClass('smallVersion');
	}*/
//}

//function resizeMenu(){
	/*J('.stepsMenu').width('100%');//reset width on resize
	if (J('#societyContainer').is('.smallVersion')) {
		J('.stepsMenu').each(function(){
			stepsHolderWidth = J(this).width();
			societyWidth = parseInt(J('#societyIcons').width()) + parseInt(J('#societyIcons').css('border-left-width')) + 1;
			stepsHolderWidth -= societyWidth;
			J(this).width(stepsHolderWidth);
		});
	}
	else {
		J('.stepsMenu').each(function(){
			stepsHolderWidth = J(this).width();
			societyWidth = parseInt(J('#societyContainer').width()) + parseInt(J('#societyContainer').css('border-left-width'));
			stepsHolderWidth -= societyWidth;
			J(this).width(stepsHolderWidth);
			J('#societyContainer').css('margin-left', stepsHolderWidth);
		});
	}*/
//}

//function resizeTab(){
	/*J('.stepsMenu').each(function(){
		stepsHolderWidth = J(this).width();
		stepsMenu = J(this).children('li');
		stepUnselectedWidth = stepsMenu.filter(':not(.selected)').width();
		stepSelectedWidth = stepsHolderWidth - (stepsMenu.length - 1) * stepUnselectedWidth - 1;
		stepsMenu.filter('.selected').width(stepSelectedWidth + 'px');
		stepsMenu.children('.stepContent').width(stepSelectedWidth + 'px');
	});*/
//}

function bizplaceAlert(msg){
	if(J('.alert').length < 1){
		var code = '<div style="display: none;" class="alert" title="Kliknij by zamknąć"><span class="arrow"></span><strong>' + msg +'</strong></div>';
		J('#content').before(code);
		J('.alert').slideDown(300).click(hideBizplaceAlert);
	}
	else{
		var alert = J('.alert');
		if(alert.is(':hidden'))
			alert.append('<strong>' + msg + '</strong>').slideDown(300);
		else
			alert.append('<strong>' + msg + '</strong>');
	}
	setTimeout(hideBizplaceAlert, 20000);
}
function hideBizplaceAlert(){
	J('.alert').slideUp(150, function(){
		J(this).html('<span class="arrow"></span>')
	});
}

/********** PURE extend *********************/
if (pure) {
	pure.initialize = function() {
		if (!pure.sandbox)
			pure.sandbox = jQuery('<div id="pureSandbox' + Math.round(Math.random()*10e16) + '" style="display: none;"></div>').appendTo('body');
	}
	/**
	 * html - templatka html do uzupełnienia przez Pure
	 * destination - gdzie wyrenderowaną templatke mamy wsadzić
	 * data - dane do obrobienia
	 * directives - jak obrabiać dane / jak uzupełniać templatkę
	 */
	pure.renderTemplate = function(html, destination, data, directives) {
		destination = jQuery(destination);
		if (html == '' || typeof html != 'string' || destination.length < 1 || !pure.sandbox)
			return false;
		var template = jQuery('<div id="pureTemplate' + Math.round(Math.random()*10e16) + '">' + html + '</div>');
		template.appendTo(this.sandbox);
		template = template.render(data, directives);
		template.children().appendTo(destination);
		return true;
	}
}


/********** AJAX shop *******************/
bizplace.JSON = function(data, callback) {
	J.get("/shop/json.php", {data: JSON.stringify(data)}, callback, "json");
};


/***********************************  VALIDATION  ******************/
// Password strength meter
// This jQuery plugin is written by firas kassem [2007.04.05]
// Firas Kassem  phiras.wordpress.com || phiras at gmail {dot} com
// for more information : http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/

var shortPass = 0;
var badPass = 1;
var goodPass = 2;
var strongPass = 3;

function passwordStrength(password, username)
{
    score = 0 

    //password < 8
    if (password.length < 8 ) { return shortPass }
    //password == username
    if (password.toLowerCase()==username.toLowerCase()) return badPass
    
    //password length
    score += password.length * 4
    score += ( checkRepetition(1,password).length - password.length ) * 1
    score += ( checkRepetition(2,password).length - password.length ) * 1
    score += ( checkRepetition(3,password).length - password.length ) * 1
    score += ( checkRepetition(4,password).length - password.length ) * 1

    //password has 3 numbers
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5 
    
    //password has 2 sybols
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5 
    
    //password has Upper and Lower chars
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10 
    
    //password has number and chars
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15 
    //
    //password has number and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 15 
    
    //password has char and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15 
    
    //password is just a nubers or chars
    if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10 
    
    //verifing 0 < score < 100
    if ( score < 0 )  score = 0 
    if ( score > 100 )  score = 100 
    
    if (score < 34 )  return badPass 
    if (score < 68 )  return goodPass
    return strongPass
}


// checkRepetition(1,'aaaaaaabcbc')   = 'abcbc'
// checkRepetition(2,'aaaaaaabcbc')   = 'aabc'
// checkRepetition(2,'aaaaaaabcdbcd') = 'aabcd'

function checkRepetition(pLen,str) {
    res = ""
    for ( i=0; i<str.length ; i++ ) {
        repeated=true
        for (j=0;j < pLen && (j+i+pLen) < str.length;j++)
            repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen))
        if (j<pLen) repeated=false
        if (repeated) {
            i+=pLen-1
            repeated=false
        }
        else {
            res+=str.charAt(i)
        }
    }
    return res
}
function mod_streng_strip(power){
					
	switch(parseInt(power)){
		case 0:
			J('#passStreng').attr('class','').html('Za krótkie');
			break;
		case 1:
			J('#passStreng').attr('class','weak').html('Słabe');
			break;
		case 2:
			J('#passStreng').attr('class','good').html('Dobre');
			break;
		case 3:
			J('#passStreng').attr('class','strong').html('Silne');
			break;
	}
}	
function only_cipher(field)
{
    field.value = (field.value).replace(/\D/g,"");
}
/***********************************  /VALIDATION  ******************/
function round_float(x,n){
  if(!parseInt(n))
  	var n=0;
  if(!parseFloat(x))
  	return 0;
  return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}

/********** ONLOAD JS *************************/
jQuery(document).ready(function(){
	
	// font size change
//	var defaultFontSize = parseInt(J('body').css('font-size'));
//	var minFontSize = defaultFontSize - 3; //now 8px
//	var maxFontSize = defaultFontSize + 3;	//now 18px
//	J('#defaultFont').click(function(event){
//		J('body').css('font-size', defaultFontSize + 'px');
//		}
//	);
//	J('#biggerFont').click(function(event){
//		if(parseInt(J('body').css('font-size')) < maxFontSize)
//			J('body').css('font-size', (parseInt(J('body').css('font-size')) + 1) + 'px');
//		}
//	);
//	J('#smallerFont').click(function(event){
//		if(parseInt(J('body').css('font-size')) > minFontSize)
//			J('body').css('font-size', (parseInt(J('body').css('font-size')) - 1) + 'px');
//		}
//	);

	// basket
//	J('#mainBasket').hide();
//	J('#newService').hide();
//	J('#wholeBasket').css('width', 'auto');
	
	// handlery otwarcia/zwiniencia koszyka
//	J('.basketBox').click(function(event) {
//		if (J('#wholeBasket').hasClass('open')) {
//			bizplace.cartHide();
//		} else {
//			bizplace.cartHide(function() {
//				bizplace.cartShow()
//			});
//		}
//		event.stopPropagation();
//		return false;
//	});
//	J('body').click(function() {
//		if (J('#wholeBasket').hasClass('add')) 
//			bizplace.cartHide();
//	});
//	J('#mainBasket').click(function(event){
//		event.stopPropagation();
//	});
	
	//HELP slider
	J('#helpSlider').click(function(){
		J('#helpSlideContent').slideToggle(300, function() {
			if (J(this).filter(':visible').length > 0)
				J('#helpSlider').addClass('opened');
			else
				J('#helpSlider').removeClass('opened');
		});
	})
	function hideHelp(){
		J('#helpSlideContent').slideUp(300, function() {
			J('#helpSlider').removeClass('opened');
		});
	}
	if(!J.cookie('bizplace-group')){
//		J.cookie('bizplace-group', 'visited', {expires: 365, domain: '.bizplace.pl', path: '/'});
		setTimeout(hideHelp,20000);
	}
	
	J('.bottomBasket input[type="submit"]').click(function(){
//		bizplace.JSON({
//			// pobierz dane zalogowanego uzytkownika
//			clientdataget: {action: 'clientdataget'},
//		}, function(data) {
//			bizplace.goTo([
//		              bizplace.tree[bizplace.groupIndex].link,
//		              (data == false ? 'rejestracja' : 'platnosc')
//		              ]);
//		});
		
		bizplace.orderCheckout();

		//		var params = new Array();
//		params[0] = bizplace.tree[bizplace.groupIndex].link;
//		params[1] = 'platnosc';
//		bizplace.goTo(params);
//		if(zalogowany)
//			J.address.value('platnosc');
//		else
//			J.address.value('rejestracja');
	});
	
	
	//slider
//	J('#slider a').click( function(event){
//		event.preventDefault();
//		J.address.value(J(this).attr('href'));
//	});
	
	
	// init pure
	pure.initialize();
	
	//window resize
//	J(window).resize(stepsOnResize);
	
	bizplace.initialize();
	
	// ajax mouse cursor handler
	J('body').ajaxStart(function() {
		J(this).css('cursor', 'wait');
	});
	J('body').ajaxStop(function() {
		J(this).css('cursor', 'auto');
	});
	J('body').ajaxError(function() {
		J(this).css('cursor', 'auto');
	});
});

