// JavaScript Document


var base_uri = "http://dev.grid1.tv";

var changed = false;

var checkOnUnload = function() {
	
	window.onbeforeunload = function() { return "You have unsaved changes." };
	
};

var uncheckOnUnload = function() {
	
	window.onbeforeunload = null;
	
};

(function(){

	var init = function() {
		
		var showBookmarks = function() {

		var loc = $('#main-ft-right').position();
		
		
		
		var top = loc.top - $('#bookmarks-box').height() - 25;

		$('#bookmarks-box').css('top', top);

		$('#bookmarks-box').css('left', loc.left + 20 );
		
		$('#bookmarks-box').fadeIn(800, function(){
																						 
			$(document).bind('click', hideBookmarks);
			
		});

	} // end showBookmarks

	var hideBookmarks = function() {

		$('#bookmarks-box').fadeOut(800);
														 
		$(document).unbind('click', hideBookmarks);
		
	};
	
	$('#bookmark-container').show();
		
		$('#bookmark-container').live('click', showBookmarks);
		
		var bookmark_url = $('#bookmark-url').val();
		
		$.post(base_uri + '/panels/bookmark', { 'url' : bookmark_url }, function(data) {

			$('#main-block').append(data);
																																									
		});
		
		


		$('.module-interface').each(initManageModules);

		var check = $('#exit-check').val();
		
		var type = $('#node-type').val();

		var id = $('#node-id').val();
	
		lock = setInterval(updateLock, 10000);
		
		$('ul.CmsForm input,ul.CmsForm select,ul.CmsForm textarea').focus(function(){
 
				if (check) {
			
				checkOnUnload();
				
			} // end if
 
		});
		
		// $('.file-browser').live('click', loadBrowser);

		$('ul.CmsForm #submit').click(uncheckOnUnload);

		$('.switch').each(function() {
			
			var name = $(this).attr('id').split('-')[1];

			var thisClass = name.split('[')[0];

			if ($(this).val() == 0) {
				
				$('input[name="' + name + '"],select[name="' + name + '"],textarea[name="' + name + '"],input.' + thisClass + ',select.' + thisClass + ',textarea.' + thisClass).attr('disabled', true);

			} // end if

		});
	
		$('.switch').change(function(){
	
			var name = $(this).attr('id').split('-')[1];

			var thisClass = name.split('[')[0];

			if ($(this).val() == 0) {

				$('input[name="' + name + '"],select[name="' + name + '"],textarea[name="' + name + '"],input.' + thisClass + ',select.' + thisClass + ',textarea.' + thisClass).attr('disabled', true);

			} else {
				
				$('input[name="' + name + '"],select[name="' + name + '"],textarea[name="' + name + '"],input.' + thisClass + ',select.' + thisClass + ',textarea.' + thisClass).removeAttr('disabled');

			} // end if
	
		});

		$('.mediaswitch').each(function() {
			
			var name = $(this).attr('id').split('_')[0];
			
			var val = $(this).val();
			
			$('.' + name).each(function() {
			
				var name = $(this).attr('id').split('_')[1].split('-')[0];
				
				var li = $(this).parents('li').get()[0];

				if (name == 'alt') {
				
					if (val != 'image') {

						$(li).show();
						
					} else {
						
						$(li).hide();
						
					}
					
				} else {
						
					if (val == name) {
	
						$(li).show();
						
					} else {
						
						$(li).hide();
						
					}

				}

			});
			
		});
		
		
	
		$('.mediaswitch').change(function(){
	
			var name = $(this).attr('id').split('_')[0];
			
			var val = $(this).val();
			
			$('.' + name).each(function() {
			
				var name = $(this).attr('id').split('_')[1].split('-')[0];

				var li = $(this).parents('li').get()[0];
						
				if (name == 'alt') {
				
					if (val != 'image') {

						$(li).show();
						
					} else {
						
						$(li).hide();
						
					}
					
				} else {

					if (val == name) {
	
						$(li).show();
						
					} else {
						
						$('select,input,textarea', li).val('');
						
						$(li).hide();
						
					}
					
				}
			
			});
	
		});
		
		


		// setInterval(updateLock, 5000);

		// $('.element_cancel_button button').click(cancelLock);

		$(".sortable-list").each(function(){

			var id = $(this).attr('id').split('-').pop();
			
			$(this).sortable({
																																
				handle : '.sortable-' + id, 
				
				update : function () { 
	
					var module = $(this).attr('class').split(" ")[2];
					
					var order = $(this).sortable('serialize'); 
					
					$.post(base_uri + '/cms/' + module + '/order?' + order);
				
				}
			
			});

		});

		$(".image-list-output").each(function(){

			var pieces = $(this).attr('id').split('-');
			
			pieces.pop();

			pieces.pop();

			var id = pieces.join('-');
					
			$(this).sortable({
																																
				handle : '.image-list-output-sort', 
				
				update : function () { 
					
					var order = $(this).sortable('serialize');
					
					var val = $('#' + id).val();
					
					$.post(base_uri + '/cms/browser/order?' + order, { val : val }, function(response) {
																																												 
						$('#' + id).val(response);																																												 
																																												 
					});
				
				}
			
			});

		});

		$('.navigation-expand').each(initExpand);

		$('.navigation-expand').click(expandNode);

		$('.show-deleted').click(function(){
		
			var controller = $(this).attr('id').split('-').shift();
		
			if ($(this).text() == 'Show Removed') {
				
				$('#' + controller + '-container .deleted').show();

				$('#' + controller + '-purge-all').show();

				$(this).text('Hide Removed');
				
			} else {
				
				$('#' + controller + '-container .deleted').hide();
				
				$('#' + controller + '-purge-all').hide();

				$(this).text('Show Removed');

			} // end if

			$.post(base_uri + '/cms/' + controller + '/show-deleted');

		});

		$('#preview-button').click(previewContent);
		
		$('#selectsitedisplay #selectsite').each(function(){
																	 
			var f = $(this).parents('form').get()[0];
			
			$(this).change(function(){
			
			
			});
																	 
		});
		
		$('.link-list').each(function(){

			var list = this;

			$('.add-new-link', list).click(function(){
				
				var nl = $('.link-form:first', list).clone();
				
				var num = $('.link-form', list).attr('id').split("-").pop();
				
				num++;

				$('input', nl).val('');

				$('button.remove-link', nl).removeAttr('disabled');

				$('button.remove-link', nl).click(function() {

					$(this).parents('.link-form').remove();
																							 
				});
				
				$('.links', list).append(nl);
																							
			});
																	
		});
		
		$('.items-list').each(initList);
		
		$.getScript('/javascript/jquery/autocomplete.js', function() {

			$('.keyword-input').each(function(){

				var input = this;

				var options = {
					
					autoFill : true,
					mustMatch : false,
					multiple: true,
					extraParams: {
						selected: function() { return $(input).val(); }
					}
				}
	
				$(this).autocomplete("/cms/keywords/list", options);

			});

			/*

			$('.keyword-input').fcbkcomplete({
				json_url: "/cms/keywords/json",
				json_cache: false,
				filter_case: true,
				filter_hide: true,
				newel: true,
				firstselected: true
			});
			
			*/
				
		});

		$('#select-site #select_site').change(function(){
																							
			$(this).parents('form').get()[0].submit();																							
																							
		});
		
		$('.preview-module-button').click(function(){
																			
			var id = $(this).attr('id').split('-')[1];
			
			window.open(base_url + '/modules/preview/id/' + id, 'previewWindow', 'status=0,toolbar=0,location=0,menubar=0,scrollbars=1,resizable=1,width=335,height=400');
		
		});

		$("div.tabbed").show();
		
		$('#search-button').click(function(){
			alert('here');
			$('#search-form').show();
			$(this).attr('disabled', true);
		});
		
	} // end init
	
	var initList = function() {

		var list = this;

		$('.add-new-item', list).click(addNewListItem);

		$('button.add-subitem', list).click(addNewListSubitem);

		$('button.remove-item', list).click(removeListItem);

		$('button.remove-subitem', list).click(removeListSubitem);

	};

	var addNewListItem = function() {
			
		var list = $(this).parents('.items-list');
		
		var nl = $('.list-item:first', list).clone();

		var sl = $('.subitems:first', list).clone();

		var num = $('.list-item:last', list).attr('id').split("-").pop();
		
		num++;
		
		$('input', nl).val('');
		
		$(sl).html('');
		
		$(nl).attr('id', $(nl).attr('id').replace('0', num));

		$(sl).attr('id', $(sl).attr('id').replace('0', num));

		$('input', nl).attr('name', $('input', nl).attr('name').replace('[0]', '[' + num + ']'));

		$('button', nl).attr('id', $('button', nl).attr('id').replace('0', num));

		$('.list-item-block', list).append(nl);
		
		$('.list-item-block', list).append(sl);
		
		$('button.remove-item', nl).removeAttr('disabled');

		$('button.remove-item', nl).click(removeListItem);

		$('button.add-subitem', nl).click(addNewListSubitem);

	};
	
	var removeListItem = function() {
		
		var list = $(this).parents('.items-list');
		
		var id = $(this).attr('id').split("-").pop();
		
		$('#item-' + id + ',#subitems-' + id, list).remove();

	}

	var addNewListSubitem = function() {
		
		var list = $(this).parents('.items-list');

		var sublist = $(this).parents('.list-item').next('.subitems');
		
		var nl = $('.list-item:first', list).clone();
		
		var id = $(this).attr('id').split("-").pop();
		
		if ($('.list-subitem:last', sublist).length > 0) {
		
			var num = $('.list-subitem:last', sublist).attr('id').split("-").pop();
		
			num++;
			
		} else {
			
			var num = 0;
			
		}
		
		$('input', nl).val('');
		
		$('li.button:first', nl).remove();
		
		$(nl).attr('id', $(nl).attr('id').replace('item', 'subitem'));

		$(nl).attr('id', $(nl).attr('id').replace('0', id));

		$(nl).attr('id', $(nl).attr('id') + '-' + num);

		$(nl).attr('class', "list-subitem");

		$('input', nl).attr('name', $('input', nl).attr('name').replace('[0]', '[' + id + ']') + "[" + num + "]");

		$('input', nl).attr('name', $('input', nl).attr('name').replace('[item]', '[subitems]'));

		$('button', nl).attr('id', "remove-subitem-" + id + "-" + num);

		$('button', nl).attr('class', "remove-subitem");

		$('button.remove-subitem', nl).removeAttr('disabled');

		$('button.remove-subitem', nl).click(function() {

			$(this).parents('.list-subitem').remove();
																					 
		});
		
		$('#subitems-' + id, list).append(nl);
																					
	};

	var removeListSubitem = function() {
		
		var list = $(this).parents('.items-list');

		var sid = $(this).attr('id').split("-")[3];

		var id = $(this).attr('id').split("-")[2];
		
		$('#subitem-' + id + "-" + sid, list).remove();

	}

	var previewContent = function() {
		
		$(this).parents('form').each(function() {
																
			var height = $('#preview-height', this).length ? $('#preview-height', this).val() : 800;
	
			var width = $('#preview-width', this).length ? $('#preview-width', this).val() : 1000;

			var url = $('#preview-url', this).val();
		
			var data = { }

			if ($('#node-id').length > 0) {
				
				data.node_id = $('#node-id').val();
				
			} // en dif

			$('textarea,input,select', this).each(function(){
			
				var name = $(this).attr('name');
				
				if (name != "" && name != "preview") {
				
					// check to see if this element is an fckEditor
					
					var fck = false;
					
					try {
						
						if (FCKeditorAPI) fck = true;
					
					} catch(e) {
						
						fck = false;
						
					} // end try
					
					if (fck && FCKeditorAPI.GetInstance(name)) {
					
						var content = FCKeditorAPI.GetInstance(name).GetData();
						
					} else {
						
						if ($('textarea[name="' + name + '"],input[name="' + name + '"],select[name="' + name + '"]').length > 1) {
							
							var val = Array();
							
							$('textarea[name="' + name + '"],input[name="' + name + '"],select[name="' + name + '"]').each(function() {
								
								val.push($(this).val());
		
							});
							
							var content = val;
							
						} else {
						
							var content = $(this).val();
							
						} // end if

					} // end if
					
					data[name] = content;
					
				} // end if
				
			});

			data.preview = true;
			
			$.post(url, data, function(response) {
							
				var response = response.split('|');
				
				if (response[0] == 1) {
					
					window.open(response[1], 'previewWindow', 'status=1,toolbar=1,location=1,menubar=1,scrollbars=1,resizable=1,width=' + width + ',height=' + height);
					
				} else {
					
					alert(response[1]);
					
				} // end if

			});

		});
		
	} // end previewContent

	var updateLock = function() {
		
		return null;
		
		var type = $('#node-type').val();

		var id = $('#node-id').val();
		
		if (type && id) {
		
			$.post(base_uri + '/cms/lock/refresh/id/' + id + '/type/' + type);
	
		} // end if
	
	} // end updateLock

	var initExpand = function() {
		
		var id = $(this).parent().parent().attr('id').split('-')[1];
		
		if ($('#output-' + id).length > 0) {

			$(this).addClass('clickable');

			if ($('#output-' + id).hasClass('hidden')) {
				
				$('#output-' + id).hide();

				$(this).html('+');
				
			} else {
				
				$('#output-' + id).show();

				$(this).html('&ndash;');
				
			} // end if
			
		} // end if
		
	} // end initExpand
	
	var expandNode = function() {
		
		var id = $(this).parent().parent().attr('id').split('-')[1];
		
		if ($('#output-' + id).length > 0) {

			if ($('#output-' + id).hasClass('hidden')) {
				
				$('#output-' + id).show();

				$('#output-' + id).removeClass('hidden');
				
				$(this).html('&ndash;');
				
			} else {
				
				$('#output-' + id).hide();

				$('#output-' + id).addClass('hidden');
				
				$(this).html('+');
				
			} // end if
			
			var controller = $(this).parents('.list-container').attr('id').split('-')[0];
			
			$.post(base_url + '/cms/' + controller + '/expand/id/' + id);
			
		} // end if
		
	} // end expandNode

	var initManageModules = function() {
	
		var pieces = $(this).attr('id').split('-');
	
		var template_id = pieces.pop();

		var navigation_id = pieces.pop();

		var content_id = pieces.pop();
	
		var interface = this;
	
		var values = Array();
	
		$('#module-list input').each(function() {
																					
			values.push($(this).val());																					
																					
		});
		
		$.post(base_uri + '/cms/pages/sidepanels', { content_id : content_id, navigation_id : navigation_id, template_id : template_id, modules : values.toString() }, function(data, textStatus) {
		
			$(interface).html(data);
		
			$('#add-module', interface).click(addModule);

			$('.remove-module', interface).click(removeModule);

			$('#preview-module', interface).click(previewModule);

			$(".module-output").sortable({
																																
				handle : '.sortable', 
				
				update : function () { 
					
					var content = "";
					
					var order = $(this).sortable('toArray');
					
					for(x=0;x<order.length;x++) {
						
						content += '<input type="hidden" name="' + $('#element-name').val() + '" value="' + order[x].split('-').pop() + '" />';
						
					} // end for
					
					$('#module-list').html(content);

				}
			
			});

		});
	
	} // end initManageModules
	
	var refreshModuleList = function(interface, addVal) {
		
		var pieces = $(interface).attr('id').split('-');
	
		var template_id = pieces.pop();

		var navigation_id = pieces.pop();

		var content_id = pieces.pop();

		var values = Array();
	
		$('#module-list input').each(function() {
			
			name = $(this).attr('name');
			
			values.push($(this).val());																					
																					
		});
		
		if (addVal && addVal != undefined) {
		
			values.push(addVal);
			
			$('#module-list').append('<input type="hidden" name="' + $('#element-name').val() + '" value="' + addVal + '" />');
		
		} // end if
		
		$.post(base_uri + '/cms/pages/sidepanels', { content_id : content_id, template_id : template_id, navigation_id : navigation_id, modules : values.toString() }, function(data, textStatus) {
		
			$(interface).html(data);
		
			$('#add-module', interface).click(addModule);

			$('.remove-module', interface).click(removeModule);

			$('#preview-module', interface).click(previewModule);

			$(".module-output").sortable({
																																
				handle : '.sortable', 
				
				update : function () { 
					
					var content = "";
					
					var order = $(this).sortable('toArray');
					
					for(x=0;x<order.length;x++) {
						
						content += '<input type="hidden" name="' + $('#element-name').val() + '" value="' + order[x].split('-').pop() + '" />';
						
					} // end for
					
					$('#module-list').html(content);

				}
			
			});

		});
		
	} // end refreshModuleList
	
	var previewModule = function(){
		
		var select = $(this).siblings('select');
		
		var id = select.val();

		if (id != 0)
		
			window.open(base_url + '/modules/preview/id/' + id, 'previewModuleWindow', 'status=0,toolbar=0,location=0,menubar=0,scrollbars=1,resizable=1,width=335,height=400');
	
	}
	
	var addModule = function() {
		
		$(this).attr('disabled', 1);
		
		var addVal = $('#modules-select').val();
		
		var interface = $(this).parents('.module-interface');
		
		refreshModuleList(interface, addVal);

	} // end addModule
	
	var removeModule = function() {
		
		var id = $(this).attr('id').split('-').pop();

		var interface = $('#modules-select').parents('.module-interface');

		$(this).parents('.module-output').children('#node-' + id).remove();
		
		$('input[name=' + $('#element-name').val() + '][value=' + id + ']').remove();

		refreshModuleList(interface, false);

	} // end if

	$(document).ready(init);

function FCKeditor_OnComplete(editorInstance)
{
		editorInstance.Events.AttachEvent('OnSelectionChange', function(){ 

			var type = $('#exit-check').val();
	
			if (type) {
				
				checkOnUnload();
				
			}
			
		});

}

var cancelForm = function(url) {
	
	var type = $('#node-type').val();

	var id = $('#node-id').val();
	
	if (type && id) {
	
		$.post(base_uri + '/cms/lock/cancel/id/' + id + '/type/' + type, null, function(){
																																										
			location.href = url;

		});

	} else {
		
		location.href = url;
		
	} // end if

} // end updateLock

/*if ($.browser.version > 7 || !$.browser.msie) {

	Cufon.replace('h2.homepage');

} else {
	
	Cufon.replace('.grey-small-panel-bd h2');
	
}

Cufon.replace('.content h1');

Cufon.replace('.content h2');

Cufon.replace('ul.navigation-primary li a');

Cufon.replace('.navigation h3');

Cufon.replace('.sidepanel h3');

Cufon.replace('h3.title'); */
$(document).ready(function(){
$('#username-input').click(function(){
	$(this).val('');
});
$('#username-input').blur(function(){
	if ($(this).val() =='')
		$(this).val('Email');
	});
$('#search-input-element').click(function(){
	$(this).val('');
});
$('#search-input-element').blur(function(){
	if ($(this).val() =='')
		$(this).val('Keywords');
});
$('#password-clear').show();
$('#password-text').hide();

$('#password-clear').focus(function() {
    $('#password-clear').hide();
    $('#password-text').show();
    $('#password-text').focus();
});
$('#password-text').blur(function() {
    if($('#password-text').val() == '') {
        $('#password-clear').show();
        $('#password-text').hide();
    }
});
if ( $('ul.navigation-primary li.selected').prev()){
var li = $('ul.navigation-primary li.selected').prev();
	$('ul.navigation-primary li.' + li.attr('class') + ' span.right-line').css('display','none');
}
$('#video-player').each(function(){
	
			var id = $('#video-id').val();
			var home = $('#home-id').val();
			
			var url = "http://www.grid1.tv/apps/video.swf?id="+id;
			if(home)
				url = url+"&home=1";
			if (id) {
				var params = { wmode:"transparent", allowScriptAccess:"always", allowFullScreen:"true" };
				var swf = swfobject.embedSWF(url, "video-player", "722", "379", "9.0.0", null, null,params,null);

			}

});
$('#world-map').each(function(){
				var params = { wmode:"transparent", allowScriptAccess:"always" };
				var swf = swfobject.embedSWF("http://www.grid1.tv/apps/worldmap.swf", "world-map", "715", "373", "9.0.0", null, null,params,null);
});

$('p.video-player-content').show();

//drivers profiles, videos and interviews tool tips code
$('#management-list div.management-row a.tool-tips[title]').tooltip({					  
	tip:'#demoTips',					  
	effect: 'slide',
	opacity:1,
	offset: [30, 0], 
	relative:true,
	position:'top center',
	delay: 200
}).dynamic({
		bottom:{
		direction:'down',
		bounce:true
	}
});

//drivers profiles, videos and interviews tool tips code
$('#featured-list div.featured-item div.featured-item-photograph a.tool-tips[title]').tooltip({
						  
	tip:'#demotip',					  
	effect: 'slide',
	opacity:1,
	offset: [-55, 00], 
	relative:false,
	position:'top center',
	delay: 200
}).dynamic({
	bottom:{
		direction:'down',
		bounce:true
	}
});

//related videos 
$('#related-videos div.related-item div.management-item-photograph a.tool-tips[title]').tooltip({
								  
	tip:'#demotip',					  
	effect: 'slide',
	opacity:1,
	offset: [-60, 00], 
	relative:false,
	position:'top center',
	delay: 200
	
});
//front page featured videos panels tool tip code
$('#driver-video-panel div.panel-row div.panel-item-photograph a.tool-tip[title] ').tooltip({
								  
	tip:'#demotip',					  
	effect: 'slide',
	opacity:1,
	offset: [35, 00], 
	relative:false,
	position:'top center',
	delay:200
	
});
//front page drivers profile images tool tip code
$('div.profile-item-photograph a.tool-tip[title]').tooltip({
								  
	tip:'#demotip',					  
	effect: 'slide',
	opacity:1,
	offset: [35, 00], 
	relative:false,
	position:'top center',
	delay: 200
	
});
$('#drivers-front-profiles div.profile-item a.tool-tipp[title]').tooltip({
	tip:'#demotip',					   
	effect: 'slide',
	opacity:1,
	offset: [35, -00], 
	relative:true,
	position:'top center',
	delay:200
});


/*$('#related-videos div.related-item img.play-transparent').tooltip({
												tip:'#demotip',					  
 
	effect: 'slide',
	opacity:1,
	 offset: [215, 380], 
	relative:true,
	position:'top center'  
});*/
$('a.clicker').bind('click', function(ev){


	
	var selectedClass = $(this).parent('li').attr('class').split(' ');
	if (selectedClass[1] == 'selected'){
			ev.preventDefault();
		$('li.'+ selectedClass[0]+' > ul').toggle('fast');
		$('li.'+ selectedClass[0]+ ' a.clicker').toggleClass('java-selected');
	}
	/*if (selectedClass[1] == 'selected'){
		
		$('li.' + selectedClass[0] + ' > ul').hide('fast');
		$(this).parent('li').removeClass('selected');
		
	} else {
	
		$('li.' + selectedClass[0] + ' > ul').show('fast');
		$(this).parent('li').addClass('selected');
	
	}*/		
					   
	
	
});


});

})();
