/* Version 0.0.1 */
// Requires slicingtype and aid to be defined

var savedPullDownDimensionNb; 
var savedPullDownIsSpecial = 0; 
var savedPullDownName; 
var pulldownIsOpen = 0; 

var idSelection = "";

(function($) {
  $.fn.enableCheckboxRangeSelection = function() {
    var lastCheckbox = null;
    var $spec = this;
    $spec.unbind("click.checkboxrange");
    $spec.bind("click.checkboxrange", function(e) {
      if (lastCheckbox != null && (e.shiftKey || e.metaKey)) {
        $spec.slice(
          Math.min($spec.index(lastCheckbox), $spec.index(e.target)),
          Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1
        ).attr({checked: e.target.checked ? "checked" : ""});
      }
      lastCheckbox = e.target;
    });
  };
})(jQuery);

// API 
if(!liveclicker) var liveclicker={};

liveclicker.callAPI = function (url, callback)
{
    // Add format to the url if it's not there
    if (url.indexOf('format=json') < 0) {
	url += '&format=json';
    }
    // Generate a variable name and add that to the url
    url += '&var=liveclicker.api_res';

   var lcs=document.createElement('script'); 
   lcs.src=url; 
   lcs.type='text/javascript'; 
   document.getElementsByTagName('head')[0].appendChild(lcs); 
   
   liveclicker.lcCallback = callback;
   setTimeout("liveclicker.lcCheckReady()", 50);
}

liveclicker.lcCheckReady = function() {
    if (window.liveclicker.api_res) {
	liveclicker.lcCallback(window.liveclicker.api_res);
    } else {
	setTimeout("liveclicker.lcCheckReady()", 50);
    }
}

function request(callback_function)
	{
		var additionalQueryString = "";
		if (typeof extraparam1 === 'undefined') 
			{
					// undefined
			}
			else
			{
					additionalQueryString = "&extraparam1="+extraparam1; 
			}
		liveclicker.callAPI('http://static.liveclicker.net/vms/ajax/slicingmenus.php?slicingtype='+slicingtype+additionalQueryString+'&aid='+aid, callback_function);
	}

function renderdata(api_json){
	if (api_json.error) {
		alert('error: '+api_json.error['@errcode']);
	  } else if (api_json.content) {
				jQuery("#slicingmenus").html(api_json.content);
	  }
}

function resetSelection ()
	{
			idSelection = "";
			return true; 
	}

function addToSelection (myvalue)
	{
			idSelection = idSelection + myvalue + ",";
			return true; 
	}

function isInSelection (myvalue)
	{
			if(idSelection.indexOf(myvalue+",") !=-1)
				{
					return true; 
				}
				else
				{
					return false; 
				}
	}

function removeFromSelection (myvalue)
	{
			idSelection = idSelection.replace(myvalue + ",", ""); 
			return true; 
	}

function updateSelection(myvalue, action)
	{
			if (action == "add")
				{
						if (isInSelection (myvalue))
							{
									// do nothing
							}
							else
							{
									addToSelection (myvalue);
							}
				}
				else if (action == "remove")
				{
						if (isInSelection (myvalue))
							{
									removeFromSelection (myvalue); 
							}
				}
			return true; 
	}

function selectAllOptions ()
	{
			jQuery("#select_all").attr('checked', true); ; 
			jQuery(".select_item").each(function(){
						jQuery(this).attr('checked', true); 
					});
			resetSelection();
	}
	
var resetSelectionForm = function ()
	{
		jQuery(".select_item").each(function()
			{
				jQuery(this).attr('checked', false); 
				resetSelection();
			});										
	}
	
jQuery(document).ready(function(){
			
			jQuery("input.select_item").enableCheckboxRangeSelection();

			// sidebar menu (pulldown for brands)
			request(renderdata);
			
			jQuery('.menu_class_btn').livequery(function(){
						jQuery(this).click(function () {  
							var menu = jQuery(this).attr("pulldown"); 
							jQuery('#'+menu).slideToggle('medium'); 
							jQuery(this).toggleClass("menu_class_up");
							
						});  
				});  
			 
			 // =============================================
			 // slicer ============================================
			 // =============================================
			 jQuery(".slicer").livequery(function(){
					jQuery(this).click(function() {
								var isExposed = 0;
								if (jQuery(this).hasClass("exposed"))	{
										isExposed = 1;
										jQuery(".slicer").removeClass("selectedslicer");
										jQuery(this).addClass("selectedslicer");
									}
								var dimension = jQuery(this).attr("d");
								var linkLabel = jQuery(this).text(); 
								var specialPullDownNb; 
								if (dimension == "special1") {jQuery('#special1').slideToggle('medium'); dimension = "special"; specialPullDownNb = 1;}; 
								if (dimension == "special2") {jQuery('#special2').slideToggle('medium'); dimension = "special"; specialPullDownNb = 2;}; 
								if (dimension == "special3") {jQuery('#special3').slideToggle('medium'); dimension = "special"; specialPullDownNb = 3;}; 
								
								if (dimension == "macro")
									{
											var raw = Number(jQuery(this).attr("raw")); 
											var target = ""; 
											if (raw == 1)
												{
														target = "powertooledittitle"; 
												}
											else if (raw == 2)
												{
														target = "powertooleditmetadescription"; 
												}
											else if (raw == 3)
												{
														target = "powertooleditthumbnail"; 
												}
											else if (raw == 4)
												{
														target = "editwidgetlist"; 
												}
											else if (raw == 5)
												{
														target = "deletewidgets"; 
												}
											else if (raw == 6)
												{
														target = "pushtoliveclickernetwork"; 
												}
											else if (raw == 7)
												{
														target = "pushtoyoutube"; 
												}
											else if (raw == 8)
												{
														target = "pushtogooglevideo"; 
												}
											else if (raw == 9)
												{
														target = "pushtoviddler"; 
												}
											else if (raw == 40)
												{
														target = "powerassetedittitle"; 
												}
											else if (raw == 41)
												{
														target = "approveallassets"; 
												}
											else if (raw == 42)
												{
														target = "pendingallassets"; 
												}
											else if (raw == 43)
												{
														target = "rejectedallassets"; 
												}
											else if (raw == 44)
												{
														target = "bulkcreatewidget"; 
												}
											macroclick(target,idSelection); // that's the call back function
									}
									else
									{
										// ======= pulldowns
										var newText = jQuery(this).text();
										if (pulldownIsOpen == 1)
												{
													// restore the old pulldown
													if (savedPullDownIsSpecial == 1)
														{
																jQuery(".myspecial"+savedPullDownDimensionNb).text(savedPullDownName);
														}
														else
														{
																jQuery(".mydim"+savedPullDownDimensionNb).text(savedPullDownName);
														}
												}
										if (dimension == "special")
											{
												savedPullDownName = jQuery(".myspecial"+specialPullDownNb).text();
											}
											else
											{
												savedPullDownName = jQuery(".mydim"+dimension).text();
											}
										if (newText == newText.substr(0, 14))
												{
														// don't trim
												}
												else
												{
														newText = newText.substr(0, 12) + '..'; 
												}
										if (dimension == "special")
											{
													jQuery(".menu_class_btn").removeClass("menu_highlighted");
													jQuery(".myspecial"+specialPullDownNb).text(newText).removeClass("menu_class_up").addClass("menu_highlighted");
													savedPullDownDimensionNb = specialPullDownNb; 
													savedPullDownIsSpecial = 1;
											}
											else
											{
													jQuery(".menu_class_btn").removeClass("menu_highlighted");
													jQuery(".mydim"+dimension).text(newText).removeClass("menu_class_up").addClass("menu_highlighted");
													
													jQuery(".mydim"+dimension).text(newText);
													savedPullDownDimensionNb = dimension; 
													savedPullDownIsSpecial = 0;
											}
										pulldownIsOpen = 1; 
										
										// ======== value management and query
										
										
										var raw = jQuery(this).attr("raw"); 
										slicingclick(dimension,raw, jQuery(this).text()); // that's the call back function
										resetSelectionForm();
										// selectAllOptions(); 
									
										if (Number(dimension) < 0) dimension = - Number(dimension);
																		
										if (isExposed == 0)
											{
													jQuery('#dim'+dimension).slideToggle('medium'); 
											}
										jQuery('.menu_class_btn').each(function(){
												if (jQuery(this).attr("pulldown") == "dim"+dimension)
													{
															// jQuery(this).text(text); 
													}
											});
										// jQuery(this).parent().parent().text(jQuery(this).text());
								} // end if macro
						});
				});
			 
			 // =============================================
			 // macros ============================================
			 // =============================================
			 
			 resetSelectionForm(); 
			 // selectAllOptions();
			 // select item
			 jQuery(".select_item").livequery(function(){
						jQuery(this).click(function() {
								var rawid; 
								var myid; 
								resetSelection();
								jQuery(".select_item").each(function() {
											rawid = jQuery(this).attr("id"); 
											myid = Number(rawid.replace("id", ""));
											if (jQuery(this).is(':checked'))
												{
														updateSelection(myid, "add");
												}
												else
												{
														updateSelection(myid, "remove");
												}
									});
							});
					});
			jQuery("#select_all").livequery(function(){
						jQuery(this).click(function() {	
								if (jQuery(this).is(':checked'))
										{
												jQuery(".select_item").each(function()
													{
														var rawid = jQuery(this).attr("id"); 
														var myid = Number(rawid.replace("id", "")); 
														jQuery(this).attr('checked', true); 
														updateSelection(myid, "add");
												});
										}
										else
										{
												jQuery(".select_item").each(function()
													{
														jQuery(this).attr('checked', false); 
														resetSelection();
												});
										}
					 });
				});
		});

