/* Javascript for Boxing.de website
*/

var aniFlagOut = null;       // stores the animation reference
  

/* #############################
   #  admin support functions  #
   -----------------------------*/
/**
 * modify HTML, CSS to beautify the edit form
 * 
 * @param ref
 * @return
 */
function modifyEditForm(ref){
    var div = jq('#viewspace'); //? ref.parent().parent();
    var H1 = jq('#main h1');
    div.attr('id', 'tabs'); // needed for yQueryUI (tabs) 
    H1.wrap('<a href="#tabs-1"></a>'); // wrap <h1> with <a>
    var tabA = H1.parent();
    tabA.html(H1.html()); // remove <h1> tags
    tabA.next().attr('id', 'tabs-1');
    tabA.wrap('<ul></ul>').wrap('<li></li>');
    
    // remove formLib interactive action 'toggleFormFieldHelper()'
    // and define our own (if needed)
    jq('form label', ref).each(function(){
      jq(this).removeAttr('onmouseup').removeAttr('onmousedown').removeAttr('onmouseout');
      jq(this).tooltip({
        track: true,
        extraClass: 'ui-widget-header',
        bodyHandler: function(){
          var helpField = jq(this).parent().next('.field');
          var help = jq('.form-fields-help', helpField);
          return help.html();
        }
      }).hover(function(){
        jq(this).css('cursor', 'normal');
      });
    });
    
    // init multiselect 
    var minW = 500;
		if (0) {
			jq("#main select[multiple='multiple']").each(function(){
				// choose either the full version
				jq(this).addClass('multiselect');
				var sW = jq(this).width() * 2.5;
				var oW = jq('option:first', jq(this)).width();
				if (sW < minW) {
					sW = minW;
				}
				jq(this).css('width', sW + 'px');
				jq('option', jq(this)).each(function(){
					jq(this).css('width', sW + 'px');
				});
				jq(this).multiselect();
			});
	  }
    // XXX: fixme
    // init singleselect 
    /*jq("#main select[multiple!='multiple']").each( function() {
     // choose either the full version
     jq(this).addClass('multiselect');
     var sW = jq(this).width() * 2.5;
     var oW = jq('option:first', jq(this)).width();
     jq(this).css('width', sW + 'px');
     jq('option', jq(this)).each(function () {
     jq(this).css('width', sW + 'px');
     });
     jq(this).singleselect();
     });*/
    // init datepicker
    if (0) {
        var dateFields = jq('#main .field input.calendar-widget');
        dateFields.datepick({
          dateFormat: 'dd.mm.yy',
          defaultDate: '01.01.1970',
          minDate: '01.01.1900',
          // maxDate       : '31.12.1992',
          showOn: 'both',
          buttonImageOnly: true,
          buttonImage: '/www/images/calendar.png'
        });
        // init datetimepicker
        var dateFields = jq('#main .field input.calendar-time-widget');
        dateFields.datepick({
          dateFormat: 'dd.mm.yy',
          defaultDate: '01.01.1970',
          minDate: '01.01.1900',
          // maxDate       : '31.12.1992',
          showOn: 'both',
          buttonImageOnly: true,
          buttonImage: '/www/images/calendar.png'
        });
    }
    
    // init WYSIWYG editor
    //? initTinyMCE();

}


/**
 * update #main after new content loaded
 * 
 * @return
 */
function updateMainArea() {
  var editForm = jq('#main form');
  if (editForm.length) {
    editForm.each(modifyEditForm);
  }
}


/* ############################################### */






var clickedThumb  = null;
var thumbPosition = 0;
var twloop        = null;   // Twitterwall interval handle

/**
 * remove focus for clicked links
 * 
 */
function blurLinks() {
		jq('a').click(function() {
			this.blur();
		})
}


function createDialogAddComment(ref) {
	
}


function initAddButtons() {
		jq('.comments .add').dialog('open');
		alert(jq('.comments .add').length + ' links processed');
}


function initAddFormBox() {
		jq('.comments .add').click( function() {
			var box = jq('#add-form-box');
			box.css({display: 'block'});
	//		box.slideDown(500);
	//		box.css({opacity: '0.0', display: 'block'});
	//		box.animate({height: 'auto', opacity: '1.0'}, 500);
		});
}



function initSocMediaActions() {
		// enable shortUrl dialogs
		jq('#content .short-url').click( function() {
			var ref = jq(this);
			/*
			var dialog = jq(this).children('.short-url-dialog');
			if (ref.hasClass('open')) {
				dialog.slideUp();
				ref.removeClass('open');
			} else {
				dialog.slideDown();
				ref.addClass('open');
				
			}
			*/
			jq(this).children('.short-url-dialog').dialog({
				bgiframe: true,
				modal: true,
				maxHeight: 60
	//			buttons: {
	//				Ok: function() {
	//					$(this).dialog('close');
	//					initSocMediaActions();
	//				}
	//			}
			});
			return false;
		});
		
		// add target=_blank
		jq('#content .socmedia a').attr('target', '_blank');
}

/* ############################################################### */

/* ############################
 * #  complex gallery script  #
 * ############################*/

function initGalleryView(ref) {
	 /*
	  *  after the HTML for gallery-overview is created and written to the container,
	  *  this function initialize the gallery script
	  */
	  jq('#gallery-overlay').galleryView({
	    panel_width: 800,
	    panel_height: 400,
	    frame_width: 100,
	    frame_height: 100,
			nav_theme: 'light'
	  });
		// jump to clicked image
		var img = jq(jq('.filmstrip li img')[thumbPosition]).click();
}

function processData() {
	 /*
	  *  generate from existing thumbnails the overlay "GalleryView" JS-gallery
	  *  
	  *  - takes thumbnails from #gallery-view .thumb-box elements
	  *    the structure looks like this
	  *      <div class="thumb-box">
	  *        <div class="thumb-wrapper">
	  *          <a href="large url">
	  *            <img src="thumb-url" title="Title" alt="Description" />
	  *          </a>
	  *        </div>
	  *      </div>
	  *  - create from ^^ the new HTML like this
	  *      <div id="gallery-overlay">
	  *        <div class="panel"><img class="thumb" src="large-url" />
		*				   <iv class="panel-overlay">
		*				     <h2>Title</h2>
		*				     <p><span>Description</span></p>
		*				   </div>
		*				 </div>
		*        ...
	  *        <ul class="filmstrip">
	  *          <li><img src="smallthumb-url" /></li>
	  *        </ul>
	  *      </div>
	  */
	  var data = '<div id="gallery-overlay">';
		var idx  = 0;
		if ('#gallery-view .thumb-box') {
        // productiv structure
				var film = '<ul class="filmstrip">';
				jq('#gallery-view .thumb-box a img').each( function() {
            data += '<div class="panel"><img class="thumb" src="' + jq(this).attr('src').replace(/(.thumb.jpg)/gi, '.large.jpg') + '" />';
						data += '<div class="panel-overlay"><h2>' + this.title + '</h2>';
						data += '<p><span>' + jq(this).attr('alt') + '</span></p></div></div>';
						film += '<li><img src="' + jq(this).attr('src').replace(/(.thumb.jpg)/, '.smallthumb.jpg') + '" /></li>';
            if (this == clickedThumb) {
                thumbPosition = idx;
            }
						idx++; 
				});
        data += film + '</ul>';
	  }
	  else {
        // dev structure
		  	data += jq('#gallery-photos').html().replace(/.preview.jpg/gi, '.large.jpg');
		  	data += '<ul class="filmstrip">';
		  	jq('#gallery-photos img.thumb').each(function(){
			  		var src = jq(this).attr('src').replace(/.preview.jpg/gi, '.thumb.jpg');
			  		data += '<li><img src="' + src + '" /></li>';
		  	});
		  	data += '</ul>';
	  }
		data += '</div';
    return data;
}

function setupGalleryContainer(){
		/*
		 *  place computed content inside gallery-container (enable gallery)
		 *  after this -> fadein
		 */
		var gcont = jq('#gallery-container');
		var html = processData();
		gcont.html(html);
		initGalleryView(jq('#gallery-photos', gcont));
		// fix nav icon URL
		jq('.nav-next, .nav-prev').each(function(){
		    this.src = this.src.replace(/(.png)/, '.gif');
	  });
	  gcont.css({visibility: 'visible', opacity: '0.0'}).
	        animate({opacity: '1.0'}, 500);
}

function clearOverlay() {
	 /*
	  *  remove computed content from gallery-container
	  */
    jq('#gallery-container').html('').css({visibility: 'hidden'});
}

function initGallery() {
	 /*
	  * this complex procedure doing the following:
	  *  - enable dark overlay and fadein
	  *  - after fadein call setupGalleryContainer()
	  *  - if overlay is clicked -> kill the overlay
	  */
    /* --- disabled ---
    jq('#gallery-view .thumb-box a, #gallery-view img.thumb').click( function() {
        clickedThumb = this;
        jq('#desktop').css({visibility: 'visible', opacity: '0.0', zIndex: '999'}).
                       animate({opacity: ' 0.9'}, 500, setupGalleryContainer).
                       click( function() {
                          jq('#gallery-container').stop().animate({opacity: '0.0'}, 200, clearOverlay);
                          jq(this).stop().css({visibility: 'hidden', opacity: '0.0', zIndex: '0'});
                       });
			  return false; 
    });
    */
   
		Shadowbox.init({
			title           : 'Bildgalerie',
      slideshowDelay  : 3
		});
    
    var gBoxes = jq('#main .gallery-box');  /* any gallery in overview */
    if (gBoxes) {
        gBoxes.each( function() {
            var ref   = jq(this);
            var link  = ref.children('h3').children('a');
            ref.attr('lang', link.attr('href'));
            ref.attr('title', link.attr('title'));
            ref.hover(function() { jq(this).css('cursor', 'pointer'); });
            ref.click( function() { 
                window.location.href = jq(this).attr('lang');
            });
        });
    }
}


/* ############################################################### */

function updateContentArea() {
		var h1 = jq('#content h1');
		h1.replaceWith('<h2>' + h1.html() + '</h2>');
		//	jq("#add-form-box input[type='submit']").click( function() {
		//		jq('#add-form-box').slideUp(300);
		//	});
}


function initTagCloud() {
    var tags = jq('#tag-cloud a');
    // create unique list with freq values
    var freqs = jq.unique(jq.map(tags, function(elem) { return parseInt(jq(elem).attr('class')); }));
    // get min/max freq value
    var min=0, max=0;
    jq(freqs).each( function() { if (this < min) { min = this; } else if (this > max) { max = this; } });
    var minSize   = 60;
    var maxSize   = 220;
		var threshold = Math.round((maxSize - minSize) * 0.75);
		var factor  = (maxSize - minSize) / max;
    tags.each( function() {
			  var span = jq(this);
			  var size = Math.round(parseInt(span.attr('class')) * factor);  // value between minSize .. maxSize
		    span.css({fontSize: (minSize + size) + '%'});
				if (size > threshold) {
				    span.css({fontWeight: 'bold'});
				}
		});	
}


function initLinkTargets() {
    jq('#main a.external-link, ' +
		   '#main a.gm-link, ' +
		   '#networks a, ' +
			 '#worldnews a').each( function() {
            jq(this).attr('target', '_blank');
	     });
}


function updateTwitterwall(keyword) {
		var url = '/BlogContainer?getTwitterwall?kw=' + keyword;
		jq.get('url', function(data) {
		    jq('#twitterwall').htmml(data);
		});
		/*
		var url = 'http://search.twitter.com/search?q=' + keyword;
		jq.ajax({
		url: url,
		success: function(html){
						var pos1 = html.indexOf('<div id="results">');
						var pos2 = html.indexOf('<p class="clearer>', pos1);
						jq('#twitterwall').htmml(html.substring(pos1, pos2));
		    }
    });
    */
}


/*
 * init the update script for the twitterwall (default per 5 sec)
 * 
 */
function initTwitterwall(msec) {
    if (msec == 'undefined' || msec < 30000) {
        msec = 45000;
		}
		var keyword = jq('#twitterwall h2 b')[1].html();
		if (jq('#twitterwall')) {
			 twloop = setInterval('updateTwitterwall("' + jq.URLEncode(keyword) + '")', msec);
		}
}


function initVideoPics() {
		jq('a.vid-pic').each( function() {
			  var maxX      = 128;
				var maxY      =  80;
				var ref       = jq(this).css('position', 'relative');
				var img	      = jq(ref.children('img')[0]);
				if (jq('#video-view').length) {
						var imgX      = img.width() < maxX ? img.width() : maxX;
            var imgY      = img.height() < maxY ? img.height() : maxY;
				} else {
					  var imgX = img.width();
            var imgY = img.height(); 
				}
				var marginStr     = ((imgY / 2) - 35 - 9) + 'px 0 0 ' + ((imgX / 2) - 35) + 'px ';
        var marginStrBar  = (imgY - 34) + 'px 0 0 1px';
         
				var button = jq(document.createElement('img'));
				button.attr('src', '/www/images/play_button_64.png').attr('alt', 'Play Button');
        button.css({position: 'absolute', margin: marginStr, width: 'auto', opacity: '0.0'});
        var bar = jq(document.createElement('img'));
        bar.attr('src', '/www/images/video_player_bar.png').attr('alt', '');
        bar.css({position: 'absolute', margin: marginStrBar, width: 'auto', opacity: '0.0'});
        
				ref.prepend(button);
        ref.prepend(bar);
				button.animate({opacity: '1.0'}, 600);
        bar.animate({opacity: '1.0'}, 600);
		});
}


function smallDelay() {
		for (var x=0; x < 50000; x++) {
			var a = 1;
		}
}



function slideFlagOut(){
    jq('#language a img').each(function(){
        jq(this).stop().animate({marginLeft: '26px'}, 500);
    });	
}


function initLangFlags() {
	  jq('#language a img').bind('mouseover', function() {
        if (aniFlagOut) {
					  clearTimeout(aniFlagOut);
				}
				jq(this).parent().siblings('a').each(function() { 
				    jq(this).children('img').stop().animate({marginLeft: '26px'}, 100); 
				});
				smallDelay();
				jq(this).animate({marginLeft: '0px'}, 500);
		}).bind('mouseout', function() {
        aniFlagOut = setTimeout(slideFlagOut, 500);
		});	
	
}


function initCountdown(){
	  if (typeof(nextDate) != 'undefined') {
        var div1 = jq('#countdown');
        var div2 = jq('#countdown #timer');
        if (!div2[0]) {
            div2 = jq('#countdown #timer2');
        }
        if (div2) {
            var diff = nextDate - new Date();
            if (diff < (999 * 24 * 60 * 60 * 1000)) {
              if (div2) {
                div2.countdown({
                  until: nextDate,
                  format: 'dHMS'
                });
              }
              div1.css({
                opacity: '0.0',
                display: 'block'
              }).animate({
                opacity: '1.0'
              }, 1500);
            }
            else {
              // do nothing -> countdown will not be visible
              document.title = diff + ' [' + nextDate + '  ' + new Date() + ']';
            }
        }
    }
}

//===============================================

jq(document).ready( function() {	
	blurLinks();
	initLangFlags();
	// initAddFormBox();
	initSocMediaActions();
	initGallery();
	// initAddButtons();
	initTagCloud();
	initLinkTargets();
	// initTwitterwall();
	window.setTimeout('initVideoPics()', 2000);
	// window.setTimeout('initCountdown()', 1000);
})
