// startnext JavaScript Document
var nr = 49; //counter fuer activitystream
$(document).ready( function(){
	$.cookie('sn_cookies_active','1');
	$('body').ajaxError(function(){
		//alert('Das hat nicht funktioniert. Bitte wende dich an unseren Support falls das Problem weiterhin auftritt.');
	});
	
	// session verlängern alle 600 Sekunden
	setInterval(function() {
		$.get('/tycon/session_hold.php');
	}, 600000);

	/** Update h1, h2 Elements for sifr usage **/
	$('#content-wrapper h1:not(h1[class])').each(function() { /*var title = $(this).attr(class);*/ $(this).addClass("startnextH1") } );
	$('#content-wrapper h2:not(h2[class])').each(function() { /*var title = $(this).attr(class);*/ $(this).addClass("startnextH2") } );

	$('.pstatus').each(function() { $(this).children('.pinfo').css('opacity','0').css('display','block'); } );

	$(".pstatus").hover(
	  function () {
		 if ($(this).children('.pinfo:hidden')) {
			$(this).children('.pinfo').fadeTo("slow", 0.85);
		  }
	  },
	  function () {
		if ($(this).children('.pinfo:visible')) {
			$(this).children('.pinfo').fadeTo("fast", 0);
		}
	  }
	);
	/** Begin Statusbar Functions **/
	var containerwidth = 250;
	$('.more a').click(function() {
	  	$('.statusbar-box').each(function() {
			if ( $(this).children(".sbslidebox").is(":visible") ) {
				$(this).children(".sbslidebox").slideUp("slow");
				$(this).children("h4.statusbarH4").removeClass("activeH4");
			}
		});
		if ( $(this).parents(".statusbar-box").children(".sbslidebox").is(":hidden") ) {
			var containerwidth = ( ($(this).parents(".statusbar-box").width()) - 1 );
			if ( containerwidth >= 250 ) {
				$(this).parents(".statusbar-box").children(".sbslidebox").css("width",containerwidth);
				$(this).parents(".statusbar-box").children(".sbslidebox").find(".innerslidebox").css("width",containerwidth);
			}
			$(this).parents(".statusbar-box").children(".sbslidebox").slideDown("slow");
			$(this).parents(".statusbar-box").children("h4.statusbarH4").addClass("activeH4");
		}
		return false;
	});
	$('.innerslidebox h4').click(function() {
	  	if ( $(this).parents(".statusbar-box").children(".sbslidebox").is(":visible") ) {
			$(this).parents(".statusbar-box").children(".sbslidebox").slideUp("slow");
			$(this).parents(".statusbar-box").children("h4.statusbarH4").removeClass("activeH4");
		}
		return false;
	});
	$(".faqdt").click(function() {
		$(this).toggleClass('faqdtopen');
		$(".faqdt").not($(this)).removeClass('faqdtopen');
		var currentlyOpened = $(this).parent().find('.faqddopen');
		var currentDescription = $(this).next('.faqdd');
		currentDescription.toggle().toggleClass('faqddopen');
		currentlyOpened.each(function() {
			$(this).hide().removeClass("faqddopen");
		} );

		return false;
 	});
	
 	/**
 	 * Status-Wechsel-Formular (Projekte, Pages, ...)
 	 **/
	$(".status-form-container>a.toggler").click(function() {
		if( $(this).hasClass('toggler_close') ) {
			$(this).siblings(".status-form-container-wrap").slideUp('slow');
			$(this).removeClass('toggler_close');
		} else {
			$(this).siblings(".status-form-container-wrap").slideDown('slow');
			$(this).addClass('toggler_close');
		}
		return false;
	});
	
	/** End Statusbar Functions **/
	//bei Registrierung Beschreibung auf 250 Zeichen bescrhaenken
	var projectTeaserForm = $('#Projekt_starten textarea[name=project_teaser_text]');
	if( projectTeaserForm.length ){
        projectTeaserForm.keyup(function(){
            if( projectTeaserForm.val().length>500 ){
                projectTeaserForm.val(projectTeaserForm.val().substr(0,500));
            }
        });
	}

	/* function for activitystream on startpage */
	setInterval(function() {
		var toShow = (nr + 6) % 50;
		$('#activity'+nr).css('display', 'none').remove().prependTo('#activities');
		$('#activity'+toShow).fadeIn(2000);
		nr--;
		if (nr<0) nr=49;
	}, 5000);

	/* Accordion */
	$('#project_incentive_list .incentiveDescription').each(function() { $(this).addClass("incentiveDescriptionClosed") } );
	$('#project_incentive_list h3.incentiveTitle').each(function() { $(this).css('cursor','pointer') } );
	$('#project_incentive_list .openOptionDescription').each(function() { 	
		$(this).addClass("openOptionDescriptionJS").removeClass("openOptionDescription").attr("title","Beschreibung lesen");
	} );
	$("#project_incentive_list span.openOptionDescriptionJS").click(function() {
		var thecontainer = $(this).parent().siblings(".incentiveDescription");
		if (thecontainer.is(":hidden")) {
			thecontainer.slideDown(200);
			$(this).addClass("closeOptionDescription").attr("title","Beschreibung schließen");
 		} else {
			thecontainer.slideUp(200);
			$(this).removeClass("closeOptionDescription");
		}
	});
	
	$("#project_incentive_list h3.incentiveTitle").click(function() {
		var thecontainer = $(this).siblings(".incentiveDescription");
		if (thecontainer.is(":hidden")) {
			thecontainer.slideDown(200);
			$(this).siblings(".checkoptionR").children('span.openOptionDescriptionJS').addClass("closeOptionDescription").attr("title","Beschreibung schließen");
 		} else {
			thecontainer.slideUp(200);
			$(this).siblings(".checkoptionR").children('span.openOptionDescriptionJS').removeClass("closeOptionDescription");
		}
	});
	
	$('a[rel=popin]').click(function(ev){
		var link = $(this);
		var contentLinkPopin = new $.simplePopIn({
			"popin_close_btn_class":'imagethumb_popin_close_btn'
		});
		contentLinkPopin.open('/..'+link.attr('href')+' #content');
		return false;
	});
	
	$(':button, a.loaderBtn').click(function(){
		var btn = $(this);
		var loaderText = btn.next('.loader');
		if( loaderText.length ) {
			btn.hide();
			loaderText.show();
			setTimeout(function(){ 
				btn.show();
				loaderText.hide();
			}, 10000);
		}
	});
	$('form.loader-submit').submit(function(){
		var submitBtn = $(this).find(':submit');
		if( submitBtn.length ) {
			var loaderText = submitBtn.next('.loader');
			if( loaderText.length ) {
				submitBtn.hide();
				loaderText.show();
				setTimeout(function(){ 
					submitBtn.show();
					loaderText.hide();
				}, 10000);
			}
		}
	});
	
	
	initTabNavigation();
	
	var mytyObj = {basePath:'/tycon',session:{id:''}};
	if( typeof myty != "undefined" ) {
		mytyObj = myty;
	}
	var isHttps = false;
	var domainHtml = "";
	if( window.location.href.indexOf("https") !== -1 ){
		isHttps = true;
	}
	
	if( window.location.href.indexOf("www.startnext.de") !== 0 ){
		domainHtml += '<img src="' + (isHttps?"https":"http") + '://www.startnext.de/templates/domain_sync_new.php?session=' + mytyObj.session.id + '" width="1" width="1" border="0"/>';
	}
	if( window.location.href.indexOf("www.startnext.at") !== 0 ){
		domainHtml += '<img src="' + (isHttps?"https":"http") + '://www.startnext.at/templates/domain_sync_new.php?session=' + mytyObj.session.id + '" width="1" width="1" border="0"/>';
	}
	if( window.location.href.indexOf("www.nordstarter.org") !== 0 ){
		domainHtml += '<img src="' + (isHttps?"https":"http") + '://www.nordstarter.org/templates/domain_sync_new.php?session=' + mytyObj.session.id + '" width="1" width="1" border="0"/>';
	}
	$('body').append(domainHtml);
});

var priceConverter = {
	convertTo : function(stringVal) {
		if( typeof stringVal != "undefined" ) {
			var lastSeperatorIndex = Math.max( stringVal.lastIndexOf(','), stringVal.lastIndexOf('.') );
			if( lastSeperatorIndex >= 0 ) {
				var dec = parseFloat('0.'+stringVal.substr(lastSeperatorIndex+1));
				var num = parseInt(stringVal.substr(0,lastSeperatorIndex).replace(/[\.,]/,''));
				if( isNaN(num) ) num = 0;
				if( isNaN(dec) ) dec = 0;
				var number = num+dec;
			} else {
				var number = parseFloat(stringVal);
			}
			return (isNaN(number) ? 0 : number);
		}
		return 0.00;
	},
	convertFrom : function(doubleVal,precision){
		var tSep = ',',dSep='.';
		switch( tyState.lang ) {
			case 'de':
				tSep = '.'; dSep = ','; break;
		}
		var precision = precision || 2;
			doubleVal = doubleVal.toFixed(precision) + '';
		x = doubleVal.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? dSep + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + tSep + '$2');
		}
		return x1 + x2;
	}
}

var snFBLogin = { 
	showAutoLoginForm : false,
	lastResponse : null,
	ajaxURL : '/../templates/jquery/user/facebook/fb-connect.php',
	fbSession : null,
	popin : null,
	autoLoginTimeout : null,
	enableAutoLoginForm : function(){
		snFBLogin.showAutoLoginForm = true;
	},
	onClickLoginLink : function(){
		if(snFBLogin.showAutoLoginForm ){
			var fbLoginSP = new $.simplePopIn();
			fbLoginSP.open(this.ajaxURL, {"action" : "showAutoLoginForm", "fbUID" : this.fbSession.userID});
			return false;
		}
		return true;
	},
	setAutoLoginStatus: function(status,callback){
		$.getJSON(this.ajaxURL, {"action" : "setAutoLoginStatus", "fbUID" : this.fbSession.userID , "status" : status} , function(){if ( $.isFunction( callback ) ){callback.call();}} );
	},
	onFBLoginActive : function(session){
		this.fbSession = session;
		$.getJSON(this.ajaxURL, {"action" : "checkAutoLogin", "fbUID" : this.fbSession.userID} , function(response){snFBLogin.onAjaxResponse(response);} );
	},
	onAjaxResponse : function(response){
		snFBLogin.lastResponse = response;
		if ( $.isFunction( snFBLogin[response.result['nextAction']] ) ){snFBLogin[response.result['nextAction']].call();}
	},
	startAutoLogin : function(){
		if(snFBLogin.lastResponse !== null && $.trim(snFBLogin.lastResponse['data']['html']) != ''){
			snFBLogin.popin = new $.simplePopIn();
			snFBLogin.popin.message( snFBLogin.lastResponse['data']['html'], function(){$('.simplepopin_close_btn')} );
			snFBLogin.popin.closeBtn.click(snFBLogin.abortAutoLogin);
			snFBLogin.autoLoginTimeout = window.setTimeout('snFBLogin.execAutoLogin();',3000);
		}else{
			snFBLogin.execAutoLogin();
		}
	},
	execAutoLogin : function(){
		document.location.href = $('a.registerlink-fb').attr('href');
	},
	abortAutoLogin : function(){
		if(snFBLogin.autoLoginTimeout !== null){
			window.clearTimeout(snFBLogin.autoLoginTimeout);
		}
		snFBLogin.popin.close();
		snFBLogin.setAutoLoginStatus(0);
	},
	showLoginError: function(){
		var fbErrorSP = new $.simplePopIn();
		fbErrorSP.open(this.ajaxURL, {"action" : "showLoginError"});
	}
};

var initTabNavigation = function() {
	$('.tab-navigation a[rel]:not(.tab-act)').unbind('click').click(function(){
		var relAttr = $(this).attr('rel');
		if( relAttr.length && $('#'+relAttr).length ) {
			$(this).parents('.tab-navigation').siblings('.tab-content-container').children('.tab-content').hide();
			$('#'+relAttr).show();
			$(this).parents('.tab').siblings().removeClass('tab-act');
			$(this).parents('.tab').addClass('tab-act');
		}
		return false;
	});
}
