// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


function update_text_position(drag) {
	
    id = drag.id.substring(drag.id.indexOf("_") + 1);

    new Ajax.Request('/composition/update_options', 
    { 	asynchronous:true, 
        evalScripts:true, 
        parameters: 'text_content[position_x]=' + Element.getStyle(drag.id, 'left') + 
                    '&text_content[position_y]=' + Element.getStyle(drag.id, 'top') +
                    '&id=' + id
    });
}

function update_text_position2(draggable) {
    id = draggable.substring(draggable.indexOf("_") + 1);
    new Ajax.Request('/composition/update_position', 
    { 	asynchronous:true, 
        evalScripts:true, 
        parameters: 'text_content[position_x]=' + Element.getStyle(draggable, 'left') + 
                    '&text_content[position_y]=' +Element.getStyle(draggable, 'top')+
                    '&id=' + id
    });
}

function init_switch(element, sub_id) {
    if(!element.current) {
        var id = element.id.substring(element.id.indexOf("_") + 1) * 1;
       switch_current_element(id);    
    }
    
    return false;
}


/* ----------------------------------------------------- switch_current_element 
 *
 *
 * ------------------------------------------------------------------------- */
function switch_current_element(element_id) 
{
    // ------------------------------ switch current element for menu bars
    list =  document.getElementById("elements");
    
    form = document.getElementById("text_edit");
    
    // cancel highlights for description
    description = $$("div.description_container")[0];
    description.current = null;
    description.setStyle({borderColor: "transparent"});
    
        
    // --------------------------- hide all elements above current element
    ids = "";
    var below = true, found = false;
    var last_pic, last_pic_text = null;
    for(i = 0; i < list.childNodes.length; i++)
    {   
        li = list.childNodes[i];
        if(li.id == null) continue;
        id = li.id.substring(li.id.indexOf("_") + 1) * 1;
        if(id == 0 ) continue;
             
        var el ="canvas_" + id;
        var menuitem= "item_"+id;
        var pic = document.getElementById("picture_" + id);
        
        //------------------------------------ cancel highlights
        Element.setStyle(el,{borderColor: "transparent"});
        Element.setStyle(menuitem,{backgroundColor: "transparent"});
        
        $(el).current = null;
        $("handle_" + id).hide();
        
        if(id == element_id) found = true;
        
        if (found && (pic != null && id !=element_id)) below = false; 
              
        if(below)
        {
            Element.show(el);
            if (pic != null) Element.show(pic);
        }
        else
        {
            Element.hide(el);
            if (pic != null) Element.hide(pic);
        }      
    }
    
    // ------------------------------------------ highligh current element
    if ($('item_'+element_id))
        $('item_'+element_id).setStyle({backgroundColor: "#ddddff"});
        
    var element = $('canvas_'+element_id);
    
    element.setStyle({border: "1px dashed #ffff33"});
    element.current = true;
    
    if (element.getAttribute("isdescription")!="true")
    {
        $("handle_" + element_id).show();
        makeDraggable(element.id);
    }
    switch_menu_settings(element.getAttribute("font_size"),element.getAttribute("font"),element.getAttribute("color"),element.getAttribute("bold"),element.getAttribute("italic"),element.getAttribute("effect"),element.getAttribute("duration"));
        
    //var text_id = element.childNodes[3].childNodes[1].getAttribute('id').substring(element.childNodes[3].childNodes[1].getAttribute('id').indexOf("_") + 1) * 1;;
    
    makeEditor(element.getAttribute("text_id"));
    
    var subtext_id=element.getAttribute("subtext_id");

    if(subtext_id!=0)
    	makeSubTextEditor('subtext_'+subtext_id);
    $("cid").value=element_id;
    $("cid2").value=element_id;
    
    //enable appropriate menu
	$('text_edit').setStyle({color: 'black'});
	$('text_edit').enable();
	$('composition_edit').setStyle({color: 'black'});
	$('composition_edit').enable();
    if (element.getAttribute("ispicture")=="true")
    	$("element_effect").disable();
    return false;
}

/* ------------------------------------------------------- switch_menu_settings 
 *
 *
 * ------------------------------------------------------------------------- */ 
function switch_menu_settings(font_size, font, color, bold, italic,effect,duration) 
{
    menu = "text_edit";
    
    // disable menu if curr element is not found (that should mean curr 
    // element is a picture)
    /*if(curr == null)
    {
        $(menu).setStyle({color: 'gray'});
        $(menu).disable();
        return false
    }*/

    $(menu).setStyle({color: 'black'}); 
    $(menu).enable();
       
    // ---------------------------------------- get and set font size 
    $("text_content_size").selectedIndex=font_size-1;
    
    // -------------------------------------- get and set font family 
    idx=0;
    switch(font){
    case "sans-serif":idx = 0; break;
    case "serif":idx = 1; break;
    case "monospace":idx = 2; break;
    case "cursive":idx = 3; break;
    case "fantasy":idx = 4; break;
    }
 
    $("text_content_font").selectedIndex =idx;

   
    // -------------------------------------------- get and set color
   
    $("text_content_color").value = color;
    $("pick_color").setStyle({backgroundColor: color});
    $("pick_color").value = color;

    
    // ---------------------------------------- get and set font bold
    if(bold == "true")
        $("text_content_bold").checked = true;
    else
        $("text_content_bold").checked = false;
    
    // -------------------------------------- get and set font italic
    if(italic == "true")
        $("text_content_italic").checked = true;
    else
        $("text_content_italic").checked = false;
        
    // -------------------------------------- effects
    idx=0;
    switch(effect){
    case "fade":idx = 0; break;
    case "minimize":idx = 1; break;
    case "none":idx = 2; break;
    }
    $("element_effect").selectedIndex =idx;    
   
    // -------------------------------------- duration
    if(duration=='1000') 
     $("element_duration").selectedIndex =0;
    else
     $("element_duration").selectedIndex =parseInt(duration)+1;
    return false;
}

/* --------------------------------------------------- rgb_string_to_hex_string 
 *
 *
 * ------------------------------------------------------------------------- */
function rgb_string_to_hex_string(rgb)
{
    rgb = rgb.substring(rgb.indexOf("(")+1, rgb.indexOf(")"));
    colors = rgb.split(",");
    color = '#';
    for(i = 0; i < 3; i++)
        color += (colors[i] * 1).toColorPart();
    
    return color.toUpperCase();
}   

function click_toggle(element_id) {
    new Effect.Appear(element_id);
    document.onclick = new Function("new Effect.Fade('"+element_id+"')");
}


/* ----------------------------------------------------------- showDropdownMenu
 *
 *
 * ------------------------------------------------------------------------- */
function showDropdownMenu(menu_id, show_button_id, hide_button_id, position) {
    var menu = document.getElementById(menu_id);
    var button = document.getElementById(show_button_id)
    var hide_button = document.getElementById(hide_button_id)

    var left, top, sTop, sLeft;

    //[left, top] = findPos(button);
    pos = findPos(button);   
    left = pos[0];
    top = pos[1];
    
    menu.style.position = "fixed";
    menu.style.display = "block";

    // ------------------- position drop down left to the button
    if(position == "left")
    {
        sTop = top + button.offsetHeight + 1;
        sLeft = (left + button.offsetWidth) - menu.offsetWidth;
    }
    // ------------------ position drop down right to the button
    else if(position == "right")
    {
        sTop = top + button.offsetHeight + 1;
        sLeft = left
    }
    // ------------- position drop down centered with the button
    else
    {
        sTop = top + button.offsetHeight + 1;
        sLeft = left - (menu.offsetWidth - button.offsetWidth) / 2.0;
    }

    menu.style.top = sTop.toString() + "px";
    menu.style.left = sLeft.toString() + "px";
    menu.style.zIndex = "200";
    
    if(hide_button == null)
        setTimeout("document.onclick = new Function(\"hideDropdownMenu('"+ menu_id +"')\");", 600);
    else
        hide_button.onclick = new Function("Element.hide('"+ menu_id +"');");
}

function hideDropdownMenu(menu_id) {
    Element.hide(menu_id);
    document.onclick = "";
}


function hideWithDelay(element_id, delay) {
    setTimeout("Element.hide(\"" + element_id + "\");", delay * 1);
}

function selectColor(color) {
    $("text_content_color").value = color;
    $("pick_color").setStyle({backgroundColor: color});
    $("pick_color").value = color;
    $("text_edit").onsubmit();
}



/* -------------------------------------------------------------------- findPos 
 *
 *
 * ------------------------------------------------------------------------- */
function findPosOld(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}


function findPos(obj)
{
    var curleft = curtop = 0; 
    if(obj.offsetParent)
    {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        
        while(obj = obj.offsetParent) 
        {
            curtop += obj.offsetTop;
            curleft += obj.offsetLeft;
        }
    }
    else
    { 
        if(obj.x)  curleft += obj.x;
        if(obj.y)  curtop += obj.y;
    }
    return [curleft,curtop];
}



function makeDraggable(dom_id) {
    if(window.draggable != null) window.draggable.destroy();
    window.draggable = new Draggable(dom_id,{
    snap: function(x,y,draggable) {
      function constrain(n, lower, upper) {
        if (n > upper) return upper;
        else if (n < lower) return lower;
        else return n;
      }
      element_dimensions = Element.getDimensions(draggable.element);
      parent_dimensions = Element.getDimensions(draggable.element.parentNode);
      return[
        constrain(x, 0, parent_dimensions.width - element_dimensions.width),
        constrain(y, 100, parent_dimensions.height - element_dimensions.height)];
      },
    revert:false,
    endeffect:function() {update_text_position2(dom_id)}
    });
}

function makeEditor(text_id) {
    if(window.editor != null) window.editor.dispose();
    if(window.subEditor != null) window.subEditor.dispose();
    
    window.editor = new Ajax.InPlaceEditor('text_'+text_id, 
        '/composition/update_text_content?id='+text_id,
        {rows:1,cols:30, highlightcolor:'transparent', cancelLink:''}
    );
}

function makeSubTextEditor(dom_id) {
    
    var text_id = dom_id.substring(dom_id.indexOf("_") + 1) * 1;
    
    window.subEditor = new Ajax.InPlaceEditor(dom_id, 
        '/composition/update_subtext_content?id='+text_id,
        {rows:1,cols:30, highlightcolor:'transparent', cancelLink:''}
    );
}
