//jQuery.noConflict to work together with mootools	
$j = jQuery.noConflict();

////////////////////////////////////
// Social media sharing functions //
////////////////////////////////////

/*** Default comments, if no text added ***/
var default_comment_twitter = '2012 werde ich eine Ballerina!';
var default_comment_facebook1 = '2012 wird ';
/* User name goes between FB texts 1 & 2 */
var default_comment_facebook2 = ' eine Ballerina!'

/*** Twitter ***/
function open_twitter_window(twitter_url) {
    var width  = 575,
        height = 400,
        left   = ($j(window).width()  - width)  / 2,
        top    = ($j(window).height() - height) / 2,
        opts   = 'status=1, toolbar=0' +
                ',width='  + width  +
                ',height=' + height +
                ',top='    + top    +
                ',left='   + left;
   
    twitwin = window.open(twitter_url, '', opts);
    
    if(typeof(twitwin) == 'undefined') alert('Für volle Funktionalität bitte die Pop-Ups zulassen. Im Safari: &#8679;&#8984;K');
    
    return false;
}

/*** Facebook ***/
function open_fb_window_async( fb_url, tag_comment ) {
	FB.ui({
		method: 'feed',
		display: 'popup',
		name: tag_comment,
		link: fb_url,
		caption: 'Für verantwortungsvolle Unbekümmertheit, durchdachte Schritte oder gar Sprünge sowie die graziöse Leichtigkeit:',
        description: 'mooz.de/2012 ',
        action_links: [{ text: 'http://mooz.de/', href: 'http://mooz.de/' }]
	});
}



function post_on_facebook() {
	attribs = $j('#tag-image-attributes');
	ias = $j('#tag-image').imgAreaSelect({ instance: true });
	
	FB.api('/me', function(response) {
		var user_name = response.name;
	
		var tag_comment = $j('#tag-share-text').val();
		if( tag_comment === '') { tag_comment = default_comment_facebook1 + user_name + default_comment_facebook2; $j('#tag-share-text').val(tag_comment); }
		var serialized = $j('#tag-image-form').serialize();
		
		$j.ajax({
			type: 'POST',
			url: 'templates/mooz-0.2.0/tags-lib/tags.php',
			data: { tag_data: serialized, action: 'add' },
			success: function(data) {
				if( data != '' ) {
					fb_url_temp = 'http://mooz.de/?tag=' + data;
					fb_url = encodeURI( fb_url_temp );
					open_fb_window_async(fb_url, tag_comment);
					ias.setSelection(140, 220, 200, 310, true); ias.setOptions({ hide: true, show: false }); ias.update();
					$j('#tag-share-text').val('');
					attribs.addClass('hidden'); attribs.css('left', 140); attribs.css('top', 310);
					$j('input#x1').val(140); $j('input#y1').val(220); $j('input#x2').val(200); $j('input#y2').val(310);
				}
			}
		});	
	});
}



//////////////////////////
// Facebook SDK (async) //
//////////////////////////

window.fbAsyncInit = function() {
	var button = $j('#facebook-button');
     	
	FB.init({ appId: '260136094040635', 
		status: true, 
		cookie: true,
		xfbml: true,
		oauth: true
	});

 	function call_facebook_api(response) {
		if (response.authResponse) {
			//user is already logged in and connected
			button.attr('onclick', 'post_on_facebook(); return false;');
		} else {
			//user is not connected to your app or logged out
			button.attr('onclick', 'FB.login(function(response) { if (response.authResponse) {	post_on_facebook(); } }); return false;');
		}
	}
	
	
	// run once with current status and whenever the status changes
	FB.getLoginStatus(call_facebook_api);
	FB.Event.subscribe('auth.statusChange', call_facebook_api);
};



//////////////////////////
// window.onload events //
//////////////////////////

$j(window).load(function() {
	
	//Define variables
	var tag_site_url, tag_pos_temp, tag_pos, tag_val, pre_tag, post_tag_pos, post_tag;
	var mouse_out_element = $j('#wo-bist-du');
	var attribs = $j('#tag-image-attributes');
	
	//Define functions
	function mouseenter_event() {
		if( ias.getSelection().width ) {
			mouse_out_element.addClass('hidden');
		    ias.setOptions({ hide: false, show: true }); ias.update();
		    attribs.css('left', ias.getSelection().x1);
		    attribs.css('top', ias.getSelection().y2);
		    attribs.removeClass('hidden');
		} else {
		    mouse_out_element.addClass('hidden');
		    ias.setSelection(140, 220, 200, 310, true);	ias.setOptions({ hide: false, show: true }); ias.update();
		    attribs.css('left', 140); attribs.css('top', 310); attribs.removeClass('hidden');
		    $j('input#x1').val(140); $j('input#x1').val(140); $j('input#y1').val(220); $j('input#x2').val(200);	$j('input#y2').val(310);
		}
	}
	
	
	//Add Facebook SDK <script/> tags & <div id="fb-root"/>
	(function(d) {
		var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
    	js = d.createElement('script'); js.id = id; js.async = true;
    	js.src = "//connect.facebook.net/en_US/all.js";
    	d.getElementsByTagName('head')[0].appendChild(js);
    	var fb = d.createElement('div'); fb.id = 'fb-root';
    	d.body.insertBefore(fb, d.body.firstChild);
	}(document));


	//Init imgAreaSelect plugin
	var ias = $j('#tag-image').imgAreaSelect({
		instance : true,
		disable : false,
		outerOpacity : 0,
		resizable : true,
		movable : true,
		zIndex : 999 ,
		onSelectEnd : function (img, selection) {
			$j('input#x1').val(selection.x1); $j('input#y1').val(selection.y1); $j('input#x2').val(selection.x2); $j('input#y2').val(selection.y2);
			attribs.css('left', selection.x1); attribs.css('top', selection.y2); attribs.removeClass('hidden');
			if ( selection.width == 0 && selection.height == 0 ) { attribs.addClass('hidden'); }
		},
		onSelectStart : function (img, selection) {
			$j('#tag-share-text-linked').addClass('hidden');
			attribs.addClass('hidden');
			$j('#tag-share-text').val('');
		},
		onSelectChange : function (img, selection) {
			attribs.css('left', selection.x1);
			attribs.css('top', selection.y2);
		}
	});
	
	
	//Create a hidden image
	ias.setSelection(140, 220, 200, 310, true); ias.setOptions({ hide: true, show: false }); ias.update();
	attribs.css('left', 140); attribs.css('top', 310);
	$j('input#x1').val(140); $j('input#y1').val(220); $j('input#x2').val(200); $j('input#y2').val(310);
	
	
	//Hover functions
	$j('#tag-image-container').mouseenter( function() { clearInterval(blinkInterval); mouse_out_element.hide(); mouseenter_event(); } );
	$j('.imgareaselect-selection').parent().mouseenter( function() { clearInterval(blinkInterval); mouse_out_element.hide(); mouseenter_event(); } );

	$j('#tag-image-container').mouseleave( function() {
			mouse_out_element.removeClass('hidden');
			ias.setOptions({ hide: true, show: false }); ias.update();
			attribs.addClass('hidden');
			blinkWoBistDu();
	});
	
	
	//WO BIST DU blink
	var blinkInterval;
	function blinkWoBistDu() {
		if(!mouse_out_element.hasClass('hidden')) {
			mouse_out_element.show();
			blinkInterval = setInterval(function(){ 
			    mouse_out_element.fadeToggle(3000);
			}, 4000);
		}
	}
	blinkWoBistDu();
	
	
	//Twitter button click action
	$j('#twitter-button').click(function() {
		var tag_comment = $j('#tag-share-text').val();
		if( tag_comment === '') { tag_comment = default_comment_twitter; $j('#tag-share-text').val(tag_comment); }
		var serialized = $j('#tag-image-form').serialize();
		
		$j.ajax({
			type: 'POST',
			url: 'templates/mooz-0.2.0/tags-lib/tags.php',
			data: { tag_data: serialized, action: 'add' },
			success: function(data) {
				if( data != '' ) {
					twitter_url = encodeURI( 'http://twitter.com/share' + '?url=http://mooz.de/?tag=' + data + '&text=' + tag_comment );
					open_twitter_window( twitter_url );
					ias.setSelection(140, 220, 200, 310, true); ias.setOptions({ hide: true, show: false }); ias.update();
					$j('#tag-share-text').val('');
					attribs.addClass('hidden'); attribs.css('left', 140); attribs.css('top', 310);
					$j('input#x1').val(140); $j('input#y1').val(220); $j('input#x2').val(200); $j('input#y2').val(310);
				}
			}
		});
		
		return false;
	});
	
	
	//When tag id is passed
	tag_site_url = window.location.href;
	tag_pos_temp = tag_site_url.search(/\/\?tag=/i);
			
	if( tag_pos_temp != -1 ) {
		tag_pos = tag_pos_temp + 6; 
		tag_val = tag_site_url.substring( tag_pos, tag_pos + 13 );
		
		mouse_out_element.addClass('hidden');
		
		$j.ajax({
			type: 'POST',
			url: 'templates/mooz-0.2.0/tags-lib/tags.php',
			data: { tag_id: tag_val, action: 'get' },
			success: function(data) {
				if( data != '' ) {
					var tag = $j.parseJSON(data);
					var tag_ias = $j('#tag-image').imgAreaSelect( { instance: true } );
					
					function mouseenter_event_linked() {
						if( tag_ias != null && tag_ias.getSelection().width ) {
							mouse_out_element.addClass('hidden');
							attribs.addClass('hidden');
						}
					}	
					
					if(tag_ias != null) {
						tag_ias.setSelection(tag.x1, tag.y1, tag.x2, tag.y2, true);
						tag_ias.setOptions({ show: true, movable: false, resizable: false });
						tag_ias.update();
					}

					$j('#tag-share-text-linked').html(tag['tag-share-text']);
					$j('#tag-share-text-linked').css('left', parseInt(tag['x1']));
					$j('#tag-share-text-linked').css('top', parseInt(tag['y2']));
					$j('#tag-share-text-linked').removeClass('hidden');
					
					$j('#tag-image').click(function() { 
						if(tag_ias != null) {
							tag_ias = null;
							$j('#tag-share-text-linked').addClass('hidden');
							
							var ias = $j('#tag-image').imgAreaSelect({
								resizable : true,
								movable : true,
							});
						}
					});
					
					$j('#tag-image-container').mouseenter( function() { mouseenter_event_linked(); } );
						$j('.imgareaselect-selection').parent().mouseenter( function() { mouseenter_event_linked(); } );

					$j('#tag-image-container').mouseleave( function() {
						if( tag_ias != null && tag_ias.getSelection().width ) {
						    tag_ias.setOptions({ show: true, hide: false });
						    mouse_out_element.addClass('hidden');
						}
					});
				}
			}
		});
		
		$j('#menu #mainMenu li a, #header h1 a').click(function() {
			tag_site_url = window.location.href;
			tag_pos_temp = tag_site_url.search(/\/\?tag=/i);
			if( tag_pos_temp != -1 ) {
				var pre_tag = tag_site_url.substring( 0, tag_pos_temp + 1 );
				var post_tag_pos = tag_site_url.search(/#/i);
				var post_tag = tag_site_url.substring( post_tag_pos ); 
				document.location.href = pre_tag + post_tag;
			}
		});
	}

});

