function log(text){ try { console.log(text); } catch (ex) { } }

$(function(){
			
	function preventClickDefaultFunc(e){ // prevent default click behavior on all A's on the page that have a pound (#) in their HTML. use event delegation to do it.
		if(this === window){ $(document.body).bind('click.prevDef', preventClickDefaultFunc);  } // bind this function as the click handler
		var sender = (e && e.target) || (window.event && window.event.srcElement), $sender = $(sender); // setup event delegation by creating the special "$sender" variable. make it cross-browser.
		if($sender.attr('href') === '#' || $sender.closest('a').attr('href') === '#') e.preventDefault(); // take into account that the sender might be a decended of "A"
	}
	
	function sideMenuHideLastLine(){  $('#sideColumnHook').children('div.categoryBox').find('em').css({visibility:'visible'}).filter(':last').removeAttr('style');  } // show devide lines while hiding the last one 
	
	function hideContactPageTitleFunc(){
		$('#contactSent').siblings('p').hide();
		$('#contactSent').parent().siblings('h1').hide();
	}
	
	function loadCookieDataFunc(){				
		var cookies 	= getCookieArrayFunc(), // put all cookies in an array
			$body 		= $(document.body),
			$homePage 	= $('#hpHook'),
			$twit 		= $('#twitterHook');
		
		if($twit.length > 0){ $twit.data('opened', true); } // twitter always gets data 
				
		//log('loading cookies:');
		for (var i in cookies){ //log(i + " : " + cookies[i] + "\n" ); // save cookie data into body.data() //cookslide
			if(i.indexOf('_Active') > -1 && $homePage.length < 1){ // check if the cookie has the special idicator "_Active" + this isn't the homepage
				var $thisID = $('#'+ i.replace("_Active", "")), // wrap in jQuery + add a pound + remove indicator
					$slideBox = $thisID.children().eq(1); // set current $slideBox shortcut
				
				//cookslidelog('"found this cookie - if index of _Active" = true\ri = '+ i + ' (key),\rcookies[i] = '+ cookies[i] +' (value)');//cookslide				
				if(cookies[i].indexOf('opened') > -1 && i.indexOf('twitter') < 0){  // if current cookie value is set to "opened" and its not twitter
					$thisID.addClass('active'); //cookslidelog('I tried to open on page load this: #'+ $thisID.attr('id'));//cookslide
				} else {
					$thisID.removeClass('active'); //cookslidelog('I tried to close on page load this: #'+ $thisID.attr('id'));//cookslide
				}
				
				if($homePage.length > 0 && i.indexOf('twitter') < 0){ // make sure all boxes are opened on the homepage on first load except twitter
					$thisID.addClass('active');
				}
				
				if(($twit.length > 0 && i.indexOf('twitter') > -1 && cookies[i].indexOf('opened') > -1)){ // if this is a twitter box AND it was set to open set active = true
					 $thisID.data().opened = true; // = save the box is opened
					//twitlog('cookie: '+ '#'+ i.replace("_Active", "") +' = '+ $thisID.data().opened);//twit
				} else if($twit.length > 0 && i.indexOf('twitter') > -1 && !$homePage.length){
					$thisID.data().opened = false;  // = save the box is closed
					//twitlog('cookie: '+ '#'+ i.replace("_Active", "") +' = '+ $thisID.data().opened);//twit
				}
				
			}//close if _Active
			
			if(i.indexOf('zoom') > -1){ // if current cookie value is set to "zoom" (remember value = TEXT ONLY!)
				$('#zoomThis').data('zoomLevel', cookies[i]); // (0 / 1 / 2)
			}
			
			if(i.indexOf('darkMode') > -1){ // if current cookie value is set to "zoom" (remember value = TEXT ONLY!)
				//darklog('found the word "darkMode" in the cookie, value = '+ cookies[i]);//dark
				$body.data('darkMode', cookies[i]); // (on, off)
				if($body.data('darkMode') === 'on'){
					$body.data().darkMode = true;
					$body.addClass('darkMode'); // add
				} else { 
					$body.data().darkMode = false;
					$body.removeClass('darkMode'); // remove
				}
				//darklog('current darkMode data value = '+ $body.data().darkMode);//dark
			}
		}//close for
		
		if($body.data('darkMode') === null){ // set default
			$body.data('darkMode', 'off');
		}
	}
	
	function slideBoxFunc(){ // dynamically open and close the side column boxes + save/retrieve individual status in a cookie
		var $slideBoxLinks 	= $('#stayConnectedHook > a:eq(0), #searchWrapperHook > a:eq(0), #servicePanelHook > a:eq(0), #eventsHook > a:eq(0)'),
			$slideBox 		= $(this).next()
			$slideWrap		= $slideBox.parent(); // slidebox wrapper shortcut
			$twitterHook 	= $('#twitterHook'),
			$twitterLink	= $twitterHook.children('a:eq(0)'),
			$twit 			= $('#twittsHook'),			
			tHeight 		= $twit.height(),
			twitTimer 		= 0,
			twitCount		= 0;
		
		function pollTwitterFunc(){
			clearTimeout(twitTimer);
			tHeight = $twit.outerHeight();
			$twit.parent().css({visibility:'hidden'});
			if(tHeight < 85){ // if no text was added by Twitter script
				twitCount++;
				if(twitCount < 30){ // terminate poll after 15 seconds
					//twitlog('looping');//twit
					twitTimer = setTimeout(pollTwitterFunc,500); // poll every half second
				}
			} else { // got text
				clearTimeout(twitTimer);
				//twitlog('twit finished loading, opened = '+ $twitterHook.data().opened);//twit
				if($twitterHook.data().opened){
					$twitterHook // now that we got the text, set height and visibility and animate open
						.data('opened', false).data('height', tHeight)
						.children('a').click(); 
					$twit.parent().removeAttr('style');
				} else { // now that we got the text, set height and visibility but keep it closed
					$twitterHook.data('opened', false).data('height', tHeight);
				}
			}
		}
		
		// on page init
		if(this === window){ 
			for(i=0; i < $slideBoxLinks.length; i++){
				$slideWrap = $slideBoxLinks.eq(i).parent();
				if($slideWrap.hasClass('active')){ // if current box has 'active' class
					$slideWrap
						.data('height', $slideBoxLinks.eq(i).next().height()) // save height
						.data('opened', true); // set true
				} else {
					$slideWrap
						.addClass('active')	 // add temporary active to save the current height
						.data('height', $slideBoxLinks.eq(i).next().height()) // save height
						.data('opened', false) // set false
						.removeClass('active'); // remove temporary active
				}
			}
			
			$slideBoxLinks.add($twitterLink).click(slideBoxFunc); // bind the click that opens and closes all slideBoxes
			$twitterHook.add('#searchWrapperHook, #stayConnectedHook, #servicePanelHook, #eventsHook').css({visibility:'visible'}); // show hidden slideBoxes on page load
			
			$twit.parent().css({position:'absolute', top:0, left:0, zIndex:-1}); // don't allow the twitter component to effect page layout until it has fully loaded
			pollTwitterFunc(); // show the other slide boxes only once: seperate polling to a special inner-function
			
		// when clicked
		} else { // close 
			if($slideWrap.data().opened){
				createCookie($slideWrap.attr('id') + '_Active', 'closed'); // set cookie value
				if(!$slideWrap.hasClass('active')){ $slideWrap.addClass('active'); } // make 100% sure that this HAS the active class
				
				$slideBox
					.find('input[type=text]').css({color:'#000'}).end() // restore black color					
					.stop(true,true).animate({height:0, opacity:0},function(){ // hide- close animation
						$slideBox
							.css({display:'none'}) // hide
							.parent()
								.removeClass('active') // change class
								.data('opened', false); // update data
					
					//twitlog('clicked, now closed? = '+ $slideWrap.data().opened);//twit
					});
			} else { // open
				createCookie($slideWrap.attr('id') + '_Active', 'opened'); // set cookie value
				$twit.parent().removeAttr('style');
				$slideWrap.addClass('active');
				$slideBox
					.stop(true,true).css({height:0, opacity:0, display:'block'}).animate({height:$slideWrap.data().height, opacity:1},function(){ // show- open animation
						$slideBox
							.find('input[type=text]').removeAttr('style'); // restore styles
						$slideWrap.data('opened', true); // show the search box background before animating height
						//twitlog('clicked, now opened? = '+ $slideWrap.data().opened);//twit
					});
			}//close run on every click
		}
	}//close slideBoxFunc
	
	// dynamically clear and re-set input values and text-color for the Search Box
	function fillClearSearchInputsFunc(e){
		var $this = $(this),
			$thisValue = $this.attr('value');

		if(e.type === 'focus'){
			if ($thisValue.length > 0){
				$this
					.attr('value','')
					.css({color:'black'});
			} else if ($thisValue === ''){ // don't change the input.value when it's loaded with data
				$this.attr('value', $this.attr('title'));
			} else if ( $thisValue != $this.attr('title') && $this.css({color:'#ACACAC'}) ){ // if a value was entered in the search box and page was refreshed - color it black.
				$this.css({color:'black'});
			}
		} else { // if blur
			if ($this.attr('value') === ''){
				$this
					.attr('value', $this.attr('title'))
					.removeAttr('style');
			}
		}//close "if event type"		
	}//close fillClearSearchInputsFunc
	
	// submit form in a new window + update values per website requirements
	function submitFormToNewWindowFunc(e){
		e.preventDefault();
		
		var newWinHref = this.action;
		var thisVal = $(this).find('input:text').val();
		if(newWinHref.indexOf('techsoup') > 0){
			var techsoup = newWinHref + thisVal;
			window.open(techsoup);
		} else {
			 var guidestar = newWinHref + '?q='+ thisVal;
			window.open(guidestar);
		}
		//newWinlog('newWinHref = '+ newWinHref +'\rthisVal = '+ thisVal +'\rtechsoup = '+ techsoup +'\rguidestar = '+ guidestar);//newWin
	}
	
	function slideTableFunc(){
		var $eventTable = $('#eventTableHook');
			$allTRs		= $eventTable.children('tbody').find('tr');
			
		if(this === window){
			
			$eventTable.find('a.title').click(slideTableFunc);	// special slide-open/close for tables.
			$allTRs.data('opened', true);
			
		} else {
			
			var $thisTR 	= $(this).closest('tr'),
				thisTRID 	= $thisTR.prevAll().length,
				nextTRID	= thisTRID + 1; // the younger brother of the father-TR of this link 
			
			//log('$thisTR = '+ $thisTR.attr('class') +'\rnextTRID = '+ nextTRID +'\rthe number of rows in $allTRs = '+ $allTRs.length + '\rcurrent data value = '+ $thisTR.data().opened);
			if($thisTR.data('opened') === true){
				$thisTR.data().opened = false;
				for(var i=nextTRID; i < $allTRs.length; i++){
					if($allTRs.eq(i).hasClass('section')) {
						setTimeout(function(){ 
							$thisTR
								.addClass('closed').removeAttr('style')
								.find('span.titleHR').hide();
						},600);
					return;
					}
					//log('for loop #'+ i +', "$allTRs.eq('+ i +').hasClass(section)" = '+ $allTRs.eq(i).hasClass('section'));// checks that this loop hasn't passed the "max allowed" rows.
					$allTRs.eq(i).children('td').each(function(){
						var $thisTRTD = $(this);
						
						$allTRs.eq(i)
							.css({background:'none'})
							.data().height = $thisTRTD.height();// get height
						
						$thisTRTD
							.filter('.eventHR').hide().end()
							.find('a').css({color:'#000'}).end()
							.wrapInner('<div/>').children('div')
							.animate({height: [0, 'swing'], opacity:0},600,function(){
								$thisTRTD
									.css({paddingTop:0, paddingBottom:0})
									.parent().addClass('hide');
							});
					});
					
					if($allTRs.eq(i).prevAll().length === $allTRs.length - 1){ // if last
						//log('Last TR was triggered = '+ $allTRs.eq(i).prevAll().length === $allTRs.length - 1);
						setTimeout(function(){ $thisTR.addClass('closed') },600);
					}
				}
			} else {
				$thisTR.data().opened = true;
				for(var i=nextTRID; i < $allTRs.length; i++){
					if($allTRs.eq(i).hasClass('section')) {
						setTimeout(function(){ 
							$thisTR
								.removeClass('closed').removeAttr('style')
								.find('span.titleHR').removeAttr('style');
						},600);
					return;
					}
					//log('inside the for loop, i = '+ i +'\rthe expression "$allTRs.eq(i).hasClass(section)" = '+ $allTRs.eq(i).hasClass('section') + '\r$allTRs.eq(i).data().height = '+$allTRs.eq(i).data().height);
					$allTRs.eq(i).children('td').each(function(){
						var $thisTRTD = $(this);
						$thisTRTD
							.parent().removeClass('hide').end()
							.removeAttr('style').css({height:0})
							.children('div').animate({height:$thisTRTD.parent().data().height, opacity:1},600,function(){
								$thisTRTD
									.removeAttr('style')
									.find('a').removeAttr('style').end()
									.parent().removeAttr('style');
								$(this).replaceWith( $(this).html() );
							});
					});
					
					if($allTRs.eq(i).prevAll().length === $allTRs.length - 1){ // if last
						//log('Last TR was triggered = '+ $allTRs.eq(i).prevAll().length === $allTRs.length - 1);
						setTimeout(function(){ $thisTR.removeClass('closed') },600);
					}
				}//end for
			}//end if($thisTR.data("opened")
		}//end if-window-else
	}//end slideTableFunc()
	
	function zoomPageFunc(){ // run and bind the zoom function
		//zoomlog('started zoom func');//zoom
		var $zoomThis 		= $('#zoomThis'),
			$feed 			= $('#feedbackHook'),
			$zoomButtons 	= $('#accessabilityHook a:eq(0), #accessabilityHook a:eq(1)');
			
		$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
		if($.browser.chrome){ $.browser.safari = false; } // update the object to correctly report chrome
		
		if(this === window){
			if(!$zoomThis.data().zoomLevel) { $zoomThis.data().zoomLevel = '0' } // if no zoom-data was defined, define default
			$zoomButtons.click(zoomPageFunc); // zoom-in 2 levels + zoom backout + take care of the "feedback" div which is on the page's edge	
		}
		
		if($(this).prevAll().length === 1){ $zoomThis.data().zoomAction = 'in'; } // if the user clicked on the 'zoom in' link
		else if(this != window && $(this).prevAll().length === 0) { $zoomThis.data().zoomAction = 'out'; }// if the user clicked on the 'zoom out' link
		
		//zoomlog('zoomLevel that was set BEFORE zoomAction was taken into account = '+ $zoomThis.data().zoomLevel);//zoom				
		if($zoomThis.data().zoomAction === 'in' && $zoomThis.data().zoomLevel >= 1){ // 1 = 1.2 // 2 = 1.7 , I used "1" and "2" for easier understanding
			$zoomThis.data('zoomLevel', '2');
			createCookie('zoomLevel', '2');
		} else if($zoomThis.data().zoomAction === 'in' && $zoomThis.data().zoomLevel <= 0){
			$zoomThis.data('zoomLevel', '1');
			createCookie('zoomLevel', '1');
		} else if($zoomThis.data().zoomAction === 'out' && $zoomThis.data().zoomLevel <= 1){
			$zoomThis.data('zoomLevel', '0');
			createCookie('zoomLevel', '0');
		} else if($zoomThis.data().zoomAction === 'out' && $zoomThis.data().zoomLevel >= 2){
			$zoomThis.data('zoomLevel', '1');
			createCookie('zoomLevel', '1');
		}
		
		//zoomlog('zoomLevel after zoomAction was set = '+ $zoomThis.data().zoomLevel);//zoom
		if($zoomThis.data().zoomLevel === '0'){
			$zoomThis.removeAttr('data-transform').add($feed).add('html').removeAttr('style'); // clean
		} else if($zoomThis.data().zoomLevel === '1'){
			//zoomlog('doing zoom level 1 = 1.2 ...');//zoom
			zoomLevel = 1.2;
			if(!$.browser.msie && !$.browser.chrome && !$.browser.opera){ //FF + all the rest
				$zoomThis.transform({ scale: [zoomLevel, zoomLevel], translateY: 84, translateX:116 }); // use the transform plugin for cross-browser compatibility
				$feed.css({left:-37});
				$zoomThis.css({margin:0});
			} else if($.browser.chrome || $.browser.msie){ //IE + chrome
				$zoomThis.css({zoom:zoomLevel});
				$('html').css({overflow:'scroll'});
			}
			
		} else if($zoomThis.data().zoomLevel === '2'){
			//zoomlog('doing zoom level 2 = 1.7 ...');//zoom
			zoomLevel = 1.7;
			if(!$.browser.msie && !$.browser.chrome && !$.browser.opera){ //FF + all the rest
				$zoomThis.transform({ scale: [zoomLevel, zoomLevel], translateY:208, translateX:233 }); // use the transform plugin for cross-browser compatibility
				$feed.css({left:-37});
				$zoomThis.css({margin:0});
			} else if($.browser.chrome || $.browser.msie){ //IE + chrome
				$zoomThis.css({zoom:zoomLevel});
				$('html').css({overflow:'scroll'});
			}
		}
	}
	
	// toggle the page skin between dark and light
	function darkLightSkinsFunc(){
		var $this = $(this),
			$body = $(document.body);
			
		if($this.prevAll().length === 3){ // if the user clicked on the 'dark skin' link
			$body.data().darkMode = true;
			createCookie('darkMode', 'on');
			//darklog('have set the darkMode cookie to "on"');
		} else if($this.prevAll().length === 2) {  // if the user clicked on the 'Light skin' link
			$body.data().darkMode = false;
			createCookie('darkMode', 'off');
			//darklog('have set the darkMode cookie to "off"');
		}
		
		//darklog('entered the darkLightSkinsFunc. the darkMode data value = '+ $body.data().darkMode);

		$body
			.append('<div id="cover"/>')
			.children('#cover').css({opacity:0}).animate({opacity:0.7},600,function(){
							
				if($body.data('darkMode')) $body.addClass('darkMode');
				else $body.removeClass('darkMode');
						
				$(this).animate({opacity:0},600,function(){
					$(this).remove();
				});
			});
	}	
	
	function open_in_new_window() {
		var	$hook = $('#contentHook'),
			$event_origin, href;
		
		$hook.bind('click._clicked_to_a_new_window', _clicked_to_a_new_window);
		
		function _clicked_to_a_new_window(event) {
			$event_origin = $(event.target).closest('a');
			
			if(_clicked_a_link()) {
				event.preventDefault();
				href = $event_origin.attr('href');
				window.open(href);
			}
		}
		
		function _clicked_a_link() {
			if($event_origin.is('a')) return true;
		}		
	}
	
	function loadLatestEventsFunc(){ // load the latest event list from the special PHP page
		var $event = $('#eventsHook');
		$event.children('div')
			.load('/NPTech/latestEventsList.php a' , function(){ // grab target div, load into it the desired page fragments: the links (a)
				$event.data('height', $event.height()) // when loading is done (on callback) : re-calculate and update saved height
			});
	}
		
	// start function binding //
	// ---------------------- //


//************************************
// Disabled for DEV work:!!
	if($('#eventsHook').length){ loadLatestEventsFunc(); } // if this is the homepage, load the latest event list from the special PHP page.
//************************************


	hideContactPageTitleFunc();	
	preventClickDefaultFunc(); // prevent default click behavior on all A's on the page that have a pound (#) in their HTML. use event delegation to do it.
	sideMenuHideLastLine(); // show devide lines while hiding the last one
	open_in_new_window(); // links that are attached to this function will open in a new window on click
	loadCookieDataFunc(); // load all cookies into $body on page load - make sure that this cookie function runs before the slideboxes does
	slideBoxFunc(); // dynamically open and close the side column boxes + save/retrieve individual cookie
	slideTableFunc(); // // dynamically open and close the event-tables
	zoomPageFunc(); // run and bind the zoom function
	
	$('#accessabilityHook a:eq(2), #accessabilityHook a:eq(3)').click(darkLightSkinsFunc); // toggle page skin between dark and light	
	$('#searchWrapperHook input[type=text]').bind('focus blur', fillClearSearchInputsFunc).trigger('focus').trigger('blur'); // dynamically clear and re-set input values and text-color for the Search Box
	$('#searchWrapperHook form').submit(submitFormToNewWindowFunc); // submit form in a new window + update values per website requirements
	
	if(document.title.indexOf('יום עיון - כלים טכנולוגיים לארגונים חברתיים - סדר יום') > -1){ // based on the given title text, do:
			$('div.innerContent').css({ direction:'ltr', padding:'0 0 0 28px'});
	}
	
	if(document.title.indexOf('testimonials') > -1){ // based on the given title text, do:
			$('h1').css({textAlign:'center', padding:'7px 0 0'});
	}
});

// Google Analytics (18-09-2011)
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-22024021-1']); // Efrat (nptech.org.il/blog)
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-22024021-2']); // Efrat (nptech.org.il)
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
