/**
 * title:            Concert Co-Op JavaScript - Common Functions
 * site:             www.wsmos.org
 * file:             java.js
 * primary author:   Junichi Furukawa
 * email:            junichi@gmail.com
 *
 * All contents copyright 2010 site496.com LLC, all rights reserved.
 **/

jQuery.fn.exists = function(){return jQuery(this).length>0;}

$(document).ready(function(){
	if($('#partners_list').exists() ){
		setInterval("slidePartners()", 2500);
	}
    
	if($('#error_bar').exists() ){
		setTimeout(function() {
			$("#error_bar").hide()
		}, 5000);
	}

	if( $('#jcrop_target').exists() ){
		$(function(){
			$('#jcrop_target').Jcrop({
				onChange: showPreview,
				onSelect: setPreview,
				minSize: [75, 75],
				aspectRatio: 1.0
			});
		});
	}

    if( $('textarea#html_content').exists() ){
		initMCE('html_content', false);
		tinyMCEmode = true;
	}


    if( $('textarea#post_text').exists() ){
      initMCE('post_text', true);
      tinyMCEmode = true;
    }

	if( $('.feed').exists() ){
		$('.feed').gFeed( { target: '#feeds', tabs: false } ); 
	} 

	if( $('.datatable').exists() ){
		$('.datatable').dataTable({
			"bSort": true,
			"bPaginate": false,
		});
	}
    
  	if( $('#image-uploader').exists() ){
		var uploader = new qq.FileUploader({
			element: document.getElementById('image-uploader'),
			action: $('#image-uploader').attr('action'),
			onComplete: function(id, fileName, result ){
				if( result.success ){
					$('#uploaded_photos').append(result.html);
				}
			}
		});           
	}

	if( $('.image_dates').exists() ){
		$('.image_dates > li > a').click( function(){
			var anchor = $(this);
			if( anchor.siblings('.side_photos').exists() ){
				anchor.siblings('.side_photos').toggle();
			}
			else {
				$.ajax({
					url: $(this).attr('href')+'?&ajax=1',
					success: function(data){
						anchor.after(data);
					}
				});
			}
			return false;
		});
	}


	if( $('#asset-uploader').exists() ){
            
		var uploader = new qq.FileUploader({
			element: document.getElementById('asset-uploader'),
			action: $('#asset-uploader').attr('action'),
			onComplete: function(id, fileName, result ){
				if( result.success ){
					$('#asset_list').append(result.html);
					add_asset_events();
				}
			}
		});  

		function add_asset_events(){
			$("#asset_list").find( 'li > a' ).each( function(){
				$(this).click(function(){
					$('#asset_url').find('textarea').val($(this).attr('href'))
					$('#asset_url').appendTo($(this)).show();
					$('#asset_url').find('textarea').focus().select(); 
		
					return false;
				});
			});
		}
		add_asset_events();
	}
    
	if( $("#tags").exists() ){      
		$("#tags").tagEditor({
			tagsBeforeField: true,
			confirmRemoval: true
		});
	}

	if( $("#map_canvas").exists() ){
		var geocoder;
		var map;

		function initialize() {
			mc = $("#map_canvas");
			var myLatlng = new google.maps.LatLng(mc.attr('lat'), mc.attr('lng'));
			var myOptions = {
				zoom: 13,
				center: myLatlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: false
			}
			var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
			var marker = new google.maps.Marker({map: map, position:
			map.getCenter()});
		}

		initialize();
	}

	if( $('.sortable').exists() ){
		$( ".sortable" ).sortable({
			opacity: 0.8,
			cursor: 'crosshair'
		});
		$( ".sortable" ).disableSelection();
	}
});
 

function slidePartners(){
  var first = $('li.first').removeClass('first');
  var obj   = $('#partners_list'); 
  obj.animate({left: '-=200px'}, 'slow', function(){
      obj.append( first.clone() );
      obj.css( 'left', '0px' );
      first.next().addClass('first').prev().remove();
    });
}


function showPreview(coords)
{
  var rx = 75 / coords.w;
  var ry = 75 / coords.h;
  var jt = $('#jcrop_target');
  
  $('#jcrop_preview').css({
    width: Math.round(rx * jt.width()) + 'px',
	height: Math.round(ry * jt.height()) + 'px',
	marginLeft: '-' + Math.round(rx * coords.x) + 'px',
	marginTop: '-' + Math.round(ry * coords.y) + 'px'
	});
};

function setPreview(c){
  showPreview(c);
  
  $('#x').val(c.x);
  $('#y').val(c.y);
  $('#w').val(c.w);
  $('#h').val(c.h);
}


function initMCE(id, light){
  tinyMCE.init({mode:"exact",
	language:"en",
	elements:id,
	cleanup : true,
	convert_newlines_to_brs: false,
	theme:"advanced",
	remove_trailing_nbsp:true,
	theme_advanced_layout_manager:"SimpleLayout",
	theme_advanced_buttons2:"",
	theme_advanced_buttons3:"",
	theme_advanced_toolbar_location:"top",
	theme_advanced_blockformats : "p,h1,h2,h3,h4,h5,h6,blockquote,code",
	content_css:"/styles/custom_tinymce.css",
	plugins:"spellchecker,safari,pagebreak,autoresize,paste",
        paste_auto_cleanup_on_paste : true,
	paste_strip_class_attributes: 'all',
	paste_remove_styles: true,
	convert_urls: true,
	relative_urls : false,
	remove_script_host : false,
	document_base_url: 'http://',
	process_html: true,
	inline_styles: true,
	gecko_spellcheck: true,
      	valid_elements:"p[style],-a[name|id|title|target|href],-blockquote[class],br,-code[class],"+"-dd[*],-dl[*],-dt[*],-del[*],-em/i[class],-ins[*],-li[*],-ol[*],-pre[class],"+"-q[*],-strong/b[class],-u[*],-ul[*],-s[*],img[*],hr[*],-sub[*],"+"-sup[*],-strike[*],-small[*],-big[*],-h1[id|class],-h2[id|class],-h3[id|class],"+"-h4[id|class],-h5[id|class],-h6[id|class],object[*],embed[*],param[*],"+"script[type|src|language|charset|defer],span[*],div[*],video[*]",
	theme_advanced_buttons1:(light?"bold,italic,sub,sup,strikethrough,separator,"+"bullist,numlist,separator,"+"justifycenter,sperator,"+"image,link,unlink,separator,"+"spellchecker,seperator,"+"pagebreak,seperator,"+"removeformat,code":"formatselect,bold,italic,sub,sup,strikethrough,separator,"+"bullist,numlist,separator,justifycenter,separator,"+"image,link,unlink,separator,"+"spellchecker,removeformat,code"),
	width:'100%'});
}

var tinyMCEmode = false;
function toogleEditorMode(sEditorID) {
    try {
        if(tinyMCEmode) {
            tinyMCE.removeMCEControl(tinyMCE.getEditorId(sEditorID));
            tinyMCEmode = false;
        } else {
	  tinyMCE.addMCEControl(document.getElementById(sEditorID), sEditorID);            tinyMCEmode = true;
        }
    } catch(e) {
        //error handling
    }
}

function toggleEditor(id) {
  if (!tinyMCE.get(id)){
    tinyMCE.execCommand('mceAddControl', false, id);
  }
  else{
    tinyMCE.execCommand('mceRemoveControl', false, id);
  }
}

