var STATE_NOT_LOADED = 0;
var STATE_LOADING    = 1;
var STATE_LOADED     = 2;

var TAGS_LOAD_STATE = STATE_NOT_LOADED;
var TAGS = [];

var CURRENT_SHOW_ID  = -1;
var TAGS_PAGE  = 0;
var TAGS_COUNT = 0;
var TAGS_PER_PAGE     = 4;

function toggle_caption(index)
{
    var div_edit    = get("captionedit" + index);
    var div_display = get("caption" + index);
    if (div_edit.style.display == "none")
    {
        div_edit.style.display = "";
        div_display.style.display = "none";
        get("title" + index).focus();
    }
    else
    {
        div_edit.style.display = "none";
        div_display.style.display = "";
    }
}

function set_slide_caption(index)
{
    toggle_caption(index);
    var obj  = get("title" + index);
    get('slide_actions').param.value = obj.value;
    slide_action(index, 'settitle');
}

function reset_slide_caption(index)
{
    toggle_caption(index);
    get("title" + index).value = get("titlecopy" + index).value;
}

function slide_action(id, action)
{
  if (lock)
    return false;

  lock = true;

  var f = get('slide_actions');
  f.elements['public'].value = is_public();
  f.tags.value   = get_tags();
  f.action.value = action;
  f.sid.value    = id;
  f.submit();
}

function is_public()
{
    var o = document.getElementById('private_yes');
    return o.checked ? 'no' : 'yes';
}

function get_tags()
{
    var o = document.getElementById('tags');
    return o.value;
}

function set_fadein()
{
    var obj  = get("fadein");
    return effect_action('fadein', obj.value);
}

function set_fadeout()
{
    var obj  = get("fadeout");
    return effect_action('fadeout', obj.value);
}

function set_background()
{
    var obj  = get("background");
    return effect_action('background', obj.value);
}

function effect_action(action, value)
{
  if (lock)
    return false;
  lock = true;

  var f = get('actions');
  f.param.value = value;
  f.action.value = action;
  f.elements['public'].value = is_public();
  f.tags.value   = get_tags();
  f.submit();
}

function do_edit_show(edit_url)
{
    document.location.href=edit_url;
}

function do_delete_slide(id, title)
{
  if (confirm('Delete slide \'' + title + '\'?'))
    return slide_action(id, 'delete');
}

function do_mute_slide(id)
{
    return slide_action(id, 'mute');
}

function do_delete_show(id)
{
  if (confirm('Delete show?'))
    return show_action(id, 'delete');
}

function do_done_show(id)
{
  var f          = get('doneform');
  get('dshowid').value = id;
  f.submit();
}

function do_post_blog(id)
{
  var f = get('blogform');
  f.sid.value = id;
  f.submit();
}

function do_done_build()
{
  if (lock)
    return false;
  lock = true;
  var f = get('doneform');
  f.tags.value   = get_tags();
  f.elements['public'].value = is_public();
  f.submit();
}

function show_action(id, action, param)
{
  var f = get('show_actions');
  f.action.value = action;
  get('ashowid').value = id;
  f.param.value  = param;
  f.submit();
}

function change_load_type(type)
{
  var u_type = get('type_upload');
  var t_type = get('type_transload');
  var f_type = get('type_flickr');

  if (u_type)
    u_type.checked = (type == 0);
  if (t_type)
    t_type.checked = (type == 1);
  if (f_type)
    f_type.checked = (type == 2);
  var params = get('upload_params');
  if (params)
    params.style.display = type == 0 ? '' : 'none';
  params = get('transload_params');
  if (params)
    params.style.display = type == 1 ? '' : 'none';
  params = get('flickr_params');
  if (params)
    params.style.display = type == 2 ? '' : 'none';
  var label = get('upload_label');
  if (label)
    label.style.display = type == 0 ? '' : 'none';
  label = get('transload_label');
  if (label)
    label.style.display = type == 1 ? '' : 'none';
  label = get('flickr_label');
  if (label)
    label.style.display = type == 2 ? '' : 'none';
  var o = get('title');
  if (o)
    o.style.display = type == 2 ? 'none' : '';
  o = get('title_label');
  if (o)
    o.style.display = type == 2 ? 'none' : '';
  o = get('hostbutton');
  if (o)
    o.style.display = type == 2 ? 'none' : '';
  switch (type)
  {
    case 1:
        o = get('url');
        if (o)
            o.focus();
        break;
    case 2:
        o = get('flickrname');
        if (o)
            o.focus();
        break;
  }

}

function init_load_type()
{
  var type = 'upload';
  var cookie = getCookie('sshow_upload_type');
  if ('transload' == cookie)
    type = 'transload';
  else
  if ('flickr' == cookie)
    type = 'flickr';

  var id = 0;
  if (type == 'transload')
    id = 1;
  else if (type == 'flickr')
    id = 2;
    
  change_load_type(id);
}

function setCookie(name, value, days)
{
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else 
    var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name)
{
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++)
  {
    var c = ca[i];
    while (c.charAt(0) == ' ') 
      c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) 
      return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function checkfile(what, upload) 
{
  if (what.value.length == 0)
  {
    alert(upload ? 'Please enter file name' : 'Please enter image URL');
    return false;
  }

  if (!upload)
  {
    if (what.value.length < 8)
    {
      alert('URL is not complete (http://sample.com/image.jpg)');
      return false;
    }
    if (what.value.substring(0, 7) != 'http://')
    {
      alert('Only HTTP URL are allowed (http://sample.com/image.jpg)');
      return false;
    }
  }
  return true;
}

function do_add_image() 
{
  if (lock)
    return false;

  var is_upload = get('type_upload').checked;
  if (is_upload)
   var what = get('fileupload');
  else
   var what = get('url');

  if (!checkfile(what, is_upload))
    return false;

  lock = true;

  if (is_upload)
    get('url').value = '';

  setCookie('sshow_upload_type', is_upload? 'upload' : 'transload', 365);
  get('upload_progress').style.display = '';
  get('upload_data').style.display = 'none';
  var f = get('hostitform');
  f.action.value = is_upload ? 'upload' : 'transload';
  f.submit();
}

function highlight(field) 
{
  field.focus();
  field.select();
}

function handle_enter(index, evt) 
{
  var keyCode = evt.which ? evt.which : evt.keyCode;
  if (keyCode == 13) 
  {
    set_slide_caption(index);
    return false;
  }
  else 
    return true;
}

function do_register()
{
  var f = get('registerform');
  if (f.email.value == "")
  {
    alert("Please enter email address");
    return false;
  }

  if (f.email.value.indexOf("@") == -1 || f.email.value.indexOf(".") == -1) 
  {
    alert("Email address entered is invalid");
    return false;
  }

  f.submit();
}

function load_thumbs(direct)
{
  for (i = 0; i < thumbs.length; i++)
  {
    if (direct)
    {      
      var target = thumbs[i][2];
      if (target == null)
        target = "_blank";

      dim1 = get_scaled_size(thumbs[i][5], thumbs[i][6], 100, 100);

      var content = '<a href="' + thumbs[i][1] + '" target ="' + target + '">';
      content += '<img src="' + thumbs[i][0] + '" style="vertical-align: middle"';
      if (thumbs[i][5])
        content += ' width="' + thumbs[i][5] + '"';
      if (thumbs[i][6])
        content += ' height="' + thumbs[i][6] + '"';
      content += ' alt="' + thumbs[i][3] + '" title="' + thumbs[i][3];
      content += '" align="center" hspace="0" vspace="0"/>';
      content += '</a>';
      id = "image_div_" + i;
      div_obj = get(id);
      div_obj.innerHTML = content;
    }
    else
      load_image(thumbs[i][0], thumbs[i][1], thumbs[i][2], thumbs[i][3], thumbs[i][4], i);
  }
}

function load_image(image_url, 
                    url,
                    target,
                    alt,
                    thumb_only,
                    index)
{
  var callback_url = '/slideshow/xmlinc.php?l=' + image_url;

  var args = [index, url, alt, target, thumb_only];

  var callback =
  {
      success:  xml_image_info_callback,
      failure:  xml_image_info_callback,
      argument: args
  };
  YAHOO.util.Connect.asyncRequest('GET', callback_url, callback, null, null);
}

function xml_image_info_callback(rsp)
{
    var links = rsp.responseXML ? rsp.responseXML.getElementsByTagName("links")[0] : null;
    if (links)
    {
      var image_link = getElementText(links, "ad_link");
      var has_thumb = (getElementText(links, "thumb_exists") == "yes");
      if(has_thumb)
      {
        preview =  getElementText(links, "thumb_link");
        var resolution   = getElementText(links, "resolution");
        dim = resolution.split('x');
        w = dim[0] * 1; // is it only way to convert string to int?
        h = dim[1] * 1;
        dim1 = get_scaled_size(w, h, 100, 100);
      }
      else
      if (rsp.argument[4])
      {
        preview = "images/thumbnail.gif";
        dim1    = [100, 85];
      }
      else
      {
        preview =  getElementText(links, "image_link");
        var resolution   = getElementText(links, "resolution");
        dim = resolution.split('x');
        w = dim[0] * 1; // is it only way to convert string to int?
        h = dim[1] * 1;
        dim1 = get_scaled_size(w, h, 100, 100);
      }
    }
    else
    {
      preview = "images/thumbnail.gif";
      dim1    = [100, 85];
    }

    var target = rsp.argument[3];
    if (target == null)
      target = "_blank";

    var url = rsp.argument[1];
    if (url == null)
      url = image_link;

    var alt   = rsp.argument[2];
    var index = rsp.argument[0];

    var content = '<a href="' + url + '" target ="' + target + '">';
    content += '<img src="' + preview + '" style="vertical-align: middle';
    content += '" width="' + dim1[0] + '" height="' + dim1[1];
    content += '" alt="' + alt + '" title="' + alt;
    content += '"/>';
    content += '</a>';
    id = "image_div_" + index;
    div_obj = get(id);


    div_obj.innerHTML = content;
}

function get_scaled_size(width, height, max_width, max_height)
{
  if (max_width < 0)
      max_width = width;
  if (max_height < 0)
      max_height = height;

  if (max_width >= width && max_height >= height)
  {
      return [width, height];
  }
  else
  {

      ratioX = max_width / width;
      ratioY = max_height / height;

      ratio = 1.0;

      if (ratioX >= ratioY && (width > max_width || height > max_height))
          ratio =  ratioY;
      else if (ratioX < ratioY && (width > max_width || height > max_height))
          ratio = ratioX;

      w = Math.floor(width * ratio);
      h = Math.floor(height * ratio);
      if (w <= 0)
        w = 1;
      if (h <= 0)
        h = 1;

      return [w, h];
  }
}

function getElementText(parent, name) 
{
    var result = parent.getElementsByTagName(name)[0];
    if (result) 
    {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) 
        {
            return result.childNodes[1].nodeValue;
        } 
        else 
        {
            return result.firstChild.nodeValue;
        }
    } 
    else 
    {
        return "n/a";
    }
}

function do_flickr()
{
    var name = get('flickrname').value;
    if (name == '')
    {
        alert('Please specify Flickr user name');
        return false;
    }
    setCookie('sshow_upload_type', 'flickr', 365);
    var frm = get('flickrform');
    frm.user.value = name;
    var sz = get('optsize');
    frm.optsize.value = sz.value; //options[sz.selectedIndex].value;
    frm.elements['public'].value = is_public();
    frm.tags.value   = get_tags();
    frm.submit();

}

function get(id)
{
    return document.getElementById(id);
}

function show(id)
{
    var o = get(id);
    if (o)
        o.style.display = '';
}

function hide(id)
{
    var o = get(id);
    if (o)
        o.style.display = 'none';
}

function remove_tag(id)
{
  var args = [id];
  var o = get('st_' + id);
  if (o)
  {
    var container = o.parentNode;
    if (container)
        container.removeChild(o);
  }
  var callback =
  {
      success:  on_remove_tag,
      failure:  on_remove_tag,
      argument: args
  };
  var url = get_api_url() + '&action=removetag&id=' + id;
  YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);
}

function on_remove_tag(rsp)
{
}

function addtags(id)
{
    var o = get('customtags' + id);
    if (!o)
        return;
    var tags = o.value;

    if (tags.length == 0)
        return;

    if (!check_tag(tags))
    {
        alert('Maximum allowed tag length is: ' + MAX_TAG_LENGTH);
        return;
    }

    var url = get_api_url() + '&action=addtag&id=' + id + '&tag=' + encodeURIComponent(tags);

    var args = [id];

    var callback =
    {
        success:  on_add_tag,
        failure:  on_add_tag,
        argument: args
    };
    YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);
}

function addtagbyid(id, tagid)
{
    hide('newtag' + id);
    show('addtag' + id);
    tagschoose(id);
    var url = get_api_url() + '&action=addtagbyid&id=' + id + '&tagid=' + tagid;
    var args = [id, tagid];

    var callback =
    {
        success:  on_add_tag_by_id,
        failure:  on_add_tag_by_id,
        argument: args
    };
    YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);
}

function on_add_tag(rsp)
{
    if (checkFault(rsp.responseXML))
        return;
    var structs = extractStructs(rsp.responseXML);
    if (!structs)
        return;           
    for (var i = 0; i < structs.length; i++)
    {
        var s = structs[i];
        var id, tname, tagid;
        for (var j = 0; j < s.length; j++)
        {
            var name = s[j]['name'];
            if (name == 'name')
                tname = s[j]['value'];
            else
            if (name == 'id')
                id = s[j]['value'];
            else
            if (name == 'tagid')
                tagid = s[j]['value'];
        }
        var found = false;
        var tnamelower = tname.toLowerCase();
        for (var j = 0; j < TAGS.length; j++)
        {
            var nlower = TAGS[j][1].toLowerCase();
            if (nlower == tnamelower)
            {
                found = true;
                break;
            }
            else
            {
                if (nlower > tnamelower)
                {
                    TAGS.splice(j, 0, [tagid, tnamelower]);
                    found = true;
                    break;
                }
            }
        }
        if (!found)
            TAGS[TAGS.length] = [tagid, tnamelower];
        html = get_tag_html(rsp.argument[0], tagid, id, tnamelower);
        var o = get('stags_' + rsp.argument[0]);
        var nt = get('nt_' + rsp.argument[0]);
        if (nt)
        {
            var container = nt.parentNode;
            if (container)
                container.removeChild(nt);
        }          
        if (o)
        {
            o.innerHTML += html;
        }
    }
}

function on_add_tag_by_id(rsp)
{
    if (checkFault(rsp.responseXML))
        return;
    var structs = extractStructs(rsp.responseXML);
    if (!structs)
        return;           
    for (var i = 0; i < structs.length; i++)
    {
        var s = structs[i];
        var id, tagid;
        for (var j = 0; j < s.length; j++)
        {
            var name = s[j]['name'];
            if (name == 'id')
                id = s[j]['value'];
            else
            if (name == 'tagid')
                tagid = s[j]['value'];
        }
        var tname;
        for (var j = 0; j < TAGS.length; j++)
        {
            if (TAGS[j][0] == tagid)
            {
                tname = TAGS[j][1];
                break;
            }
        }
        html = get_tag_html(rsp.argument[0], tagid, id, tname ? tname.toLowerCase() : tname);
        var nt = get('nt_' + rsp.argument[0]);
        if (nt)
        {
            var container = nt.parentNode;
            if (container)
                container.removeChild(nt);
        }          
        var o = get('stags_' + rsp.argument[0]);
        if (o)
        {
            o.innerHTML += html;
        }
    }
}

function get_tag_html(image_id, tag_id, image_tag_id, name)
{
    var html = '<div id="st_' + image_tag_id + '" style="display: inline">';
    html += '<a style="color: red;" href="javascript:remove_tag(' + image_tag_id + ')">[x]</a>&nbsp;';
    html += '<span id="tl_' + image_id + '_' + tag_id + '"><i>' + quote_html(name) + '</i></span>\n';
    html += '</div>\n';
    return html;
}

function set_public(id, value)
{

  if (value == 'y')
  {
      show('vis_public_' + id);
      hide('vis_private_' + id);
  }
  else
  {
      show('vis_private_' + id);
      hide('vis_public_' + id);
  }

  var url = get_api_url() + '&action=setpublic&id=' + id + '&value=' + value;
  var args = [id, value];

  var callback =
  {
      success:  on_public_set,
      failure:  on_public_set,
      argument: args
  };
  YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);
}

function on_public_set(rsp)
{
}

function set_public_all()
{

  var is_public = get('all_public').checked;
  var value = is_public ? 'y' : 'n';

  if (!confirm('Mark all your slideshows as ' + (is_public ? 'public' : 'private') + '?'))
    return;

  var url = get_api_url() + '&action=setpublicall&value=' + value;
  var args = [value];

  var callback =
  {
      success:  on_public_all_set,
      failure:  on_public_all_set,
      argument: args
  };
  YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);
}


function on_public_all_set(rsp)
{
    if (checkFault(rsp.responseXML))
        return;
    var divs = document.getElementsByTagName('span');
    if (!divs)
        return;
    var is_public = rsp.argument[0] == 'y';
    for (var i = 0; i < divs.length; i++)
    {
        if (divs[i].id && divs[i].id.length > 11 && divs[i].id.substring(0, 11) == 'vis_public_')
        {            
            var id = divs[i].id.substring(11);
            if (is_public)
            {
                show('vis_public_' + id);
                hide('vis_private_' + id);
            }
            else
            {
                show('vis_private_' + id);
                hide('vis_public_' + id);
            }
        }
    }
}


function tagschoose(id)
{
    if (id != CURRENT_SHOW_ID)
        hide('ctags' + CURRENT_SHOW_ID);

    CURRENT_SHOW_ID = id;
    TAGS_COUNT = 0;

    if (TAGS_LOAD_STATE == STATE_LOADING)
        return;

    if (TAGS_LOAD_STATE == STATE_LOADED)
    {
        var o = get('ctags' + id);
        if (!o)
            return;
        if (o.style.display == 'none')
            o.style.display = '';
        else
        {
            o.style.display = 'none';
            return;
        }

        var tagset = intersect_tags();
        TAGS_COUNT = tagset.length;
        var pages = Math.ceil(TAGS_COUNT / TAGS_PER_PAGE);
        if (pages <= TAGS_PAGE)
            TAGS_PAGE = 0;

        var html = '';
        for (var i = 0; i < tagset.length; i++)
        {
            html += '<span id="ct' + id + '_' + i + '" style="display:none;"><a href="javascript:addtagbyid(' + id + ',' + tagset[i][0] + ')">' + quote_html(tagset[i][1]) + '</a><br/></span>';
        }
        var o = get('ctagslist' + id);
        if (o)
            o.innerHTML = html;
        tagsnav(id);
        showtags(id);
        return;
    }

    TAGS_LOAD_STATE = STATE_LOADING;

    var args = [id];

    var callback =
    {
        success:  on_tags_fetched,
        failure:  on_tags_fetched,
        argument: args
    };

    var url = get_api_url() + '&action=gettags';

    YAHOO.util.Connect.asyncRequest('GET', url, callback, null, null);

}

function intersect_tags(id)
{
    var id = CURRENT_SHOW_ID;
    var prefix = 'tl_' + id + '_';
    var ret = new Array;
    for (var i = 0; i < TAGS.length; i++)
    {
        var o = get(prefix + TAGS[i][0]);
        if (!o || o.style.display == 'none')
            ret[ret.length] = TAGS[i];
    }
    return ret;
}

function on_tags_fetched(rsp)
{
    if (checkFault(rsp.responseXML))
        return;
    TAGS = new Array;
    TAGS_LOAD_STATE = STATE_LOADED;
    var structs = extractStructs(rsp.responseXML);
    if (structs)
    {
        for (var i = 0; i < structs.length; i++)
        {
            var s = structs[i];
            var id, tname;
            for (var j = 0; j < s.length; j++)
            {
                var name = s[j]['name'];
                if (name == 'name')
                    tname = s[j]['value'];
                else
                if (name == 'id')
                    id = s[j]['value'];
            }
            var tag = [id, tname ? tname.toLowerCase() : tname];
            TAGS[TAGS.length] = tag;
        }
    }
    tagschoose(CURRENT_SHOW_ID);
}

function tagsback(id)
{
    TAGS_PAGE--;
    tagsnav(id);
    showtags(id);
}

function tagsfwd(id)
{
    TAGS_PAGE++;
    tagsnav(id);
    showtags(id);
}

function tagsnav(id)
{
    var pages = Math.ceil(TAGS_COUNT / TAGS_PER_PAGE);
    if (pages <= TAGS_PAGE)
        TAGS_PAGE = 0;

    if (TAGS_PAGE > 0)
        show('ctagsback' + id);
    else
        hide('ctagsback' + id);

    if (TAGS_PAGE < pages - 1)
        show('ctagsfwd' + id);
    else
        hide('ctagsfwd' + id);
}

function showtags(id)
{
    var o = get('ctagslist' + id);
    if (!o)
        return;
    var labels = o.getElementsByTagName('span');
    if (labels)
    {
        for (var i = 0; i < labels.length; i++)
            labels[i].style.display = 'none';
    }
    var start = TAGS_PAGE * TAGS_PER_PAGE;
    var end   = (TAGS_PAGE + 1) * TAGS_PER_PAGE;
    if (end > TAGS_COUNT)
        end = TAGS_COUNT;
    for (var i = start; i < end; i++)
        show('ct' + id + '_' + i);
}

function get_api_url()
{
  var root = document.location.href;
  var pos = root.lastIndexOf('/');
  root = root.substring(0, pos);
  return root + '/dbclient.php?r=' + Math.random();
}

function do_add_tags(id)
{
    addtags(id);
    get('customtags' + id).value = '';
}

function quote_html(html)
{
    var ret = '';
    for (var i = 0; i < html.length; i++)
    {
        var c = html.charAt(i);
        switch (c)
        {
            case '>':
                ret += '&gt;';
                break;
            case '<':
                ret += '&lt;';
                break;
            case '"':
                ret += '&quot;';
                break;
            case '&':
                ret += '&amp;';
                break;
            default:
                ret += c;
        }
    }
    return ret;
}

function fake_thumb(obj)
{
    if (!obj.done)
    {
        obj.done = true;
        obj.src = 'images/thumbnail.png';
    }
}

function extract(xml, tag)
{
    var start = xml.indexOf('<' + tag + '>');
    if (start < 0)
        return null;
    xml = xml.substring(start + tag.length + 2);
    start = xml.indexOf('</' + tag + '>');
    if (start < 0)
        return null;
    return xml.substring(0, start);
}