var $had_alert = false;
function initUploads(){
  $('.files_upload').each(function(){
    var $id = $(this).attr('id')
    $(this).uploadify({
        'uploader'  : '/swf/uploadify.swf',
        'script'    : '/upload/',
        'cancelImg' : '/css/images/cancel.png',
        'multi'     : true,
        'auto'      : false,
        'scriptData': {'type' : 'film_images'},
        'fileExt'   : '*.jpg;*.jpeg;*.JPG;*.JPEG',
        'fileDesc'  : 'JPEG Image Files',
        'queueSizeLimit' : 3,
        'width'       : '180',
        'height'      : '32',
        'buttonImg'   : '/css/images/browse.jpg',
        'onInit'    : function(){
          //alternative.debug('INIT');
        },
        'onSelect'  : function(event, ID, fileObj){
          if ($('#' + $id).parent().find('img').length >=3 ){
            $('#img_err_msg').html('Maximum number of images reached.<br /> Please remove some images in order to continue uploading');
            // alternative.debug('should cancel:' + ID)
            $('#' + event.target.id).uploadifyCancel(ID);
            $('#' + event.target.id).uploadifyClearQueue();
            setTimeout(function(){$('#img_err_msg').html('')}, 3000);
            return false;
          }
        },
        'onCancel' : function(event,ID,fileObj,data){
          // alternative.debug('cancel: ' + ID);
        },
        'onOpen'  : function(event,ID,fileObj){
          // /alternative.debug('uploading:' + ID);
        },
        'onClearQueue' : function(event) {
          // alternative.debug('The queue has been cleared.');
        },
        'onComplete'  : function(event, ID, fileObj, response, data) {
          alternative.debug(response);
          $data = JSON.parse(response);
          var $hidden = $('<input type="hidden" name="img_' + $id + '[]" value="' + $data.filename + '" />')
          var $img = $('<img src="' + $data.filename + '" width="120" height="90"" />')
          var $del_btn = $('<a href="javascript:;" class="del" style="position:relative;float:none;margin:0 15px 5px -25px;">X</a>');
          $del_btn.bind('click', function(e){
            return alternative.rmImage(this);
          })
          $hidden.appendTo($('#' + $id).parent());
          $img.appendTo($('#' + $id).parent());
          $del_btn.appendTo($('#' + $id).parent());
          //$('#file_' + fileObj.id);
        },
        'onError'     : function (event,ID,fileObj,errorObj) {
          alternative.debug(errorObj.type + ' Error: ' + errorObj.info);
        }
    
      });
  });
  
  // entry dialogue
  $('#dialogue_upload').each(function(){
    var $id = $(this).attr('id')
    $(this).uploadify({
        'uploader'  : '/swf/uploadify.swf',
        'script'    : '/upload/',
        'cancelImg' : '/css/images/cancel.png',
        'multi'     : false,
        'auto'      : true,
        'scriptData': {'type' : 'film_dialogue'},
        'fileExt'   : '*.txt;*.doc;*.docx;*.pdf;*.rtf;*.TXT;*.DOC;*.DOCX;*.PDF;*.RTF',
        'fileDesc'  : 'Text documents (.txt, .pdf, .rtf, .doc)',
        'queueSizeLimit' : 3,
        'width'       : '180',
        'height'      : '32',
        'buttonImg'   : '/css/images/browse.jpg',
        'onInit'    : function(){
          //alternative.debug('INIT');
        },
        'onSelect'  : function(event, ID, fileObj){
        },
        'onCancel' : function(event,ID,fileObj,data){
          // alternative.debug('cancel: ' + ID);
        },
        'onOpen'  : function(event,ID,fileObj){
          // /alternative.debug('uploading:' + ID);
        },
        'onClearQueue' : function(event) {
          // alternative.debug('The queue has been cleared.');
        },
        'onComplete'  : function(event, ID, fileObj, response, data) {
          alternative.debug(response);
          $data = JSON.parse(response);
          var $hidden = $('#hidden_dialogue_list')
          $('#dialogue_file a').attr('href', $data.filename);
          $hidden.val($data.filename);
          //$('#file_' + fileObj.id);*/
        },
        'onError'     : function (event,ID,fileObj,errorObj) {
          alternative.debug(errorObj.type + ' Error: ' + errorObj.info);
        }
    
      });
  });
  
  initDirPicUpload();
}

function initDirPicUpload()
{
   $('.director_pic').each(function(){
    var $id = $(this).attr('id')
    attachUploadify($id)
  }); 
}

function attachUploadify($id){
    $('#' + $id).uploadify({
        'uploader'  : '/swf/uploadify.swf',
        'script'    : '/upload/',
        'cancelImg' : '/css/images/cancel.png',
        'auto'      : true,
        'multi'     : false,
        'scriptData': {'type' : 'pic_director'},
        'fileExt'   : '*.jpg;*.jpeg;*.JPG;*.JPEG',
        'fileDesc'  : 'JPEG Image Files',
        'width'       : '180',
        'height'      : '32',
        'buttonImg'   : '/css/images/browse.jpg',
        'onInit'    : function(){
          /*$('.director input[type=hidden]').each(function(){
            alternative.debug($(this).attr('id') +': ' + $(this).val());
          })
          */
          //alternative.debug('INIT');
        },
        'onComplete'  : function(event, ID, fileObj, response, data) {
          //alternative.debug(response);
          $data = JSON.parse(response);
          $('#hidden_' + $id).val($data.filename);
          $('#img_' + $id).attr('src', $data.filename);
          //$('#file_' + fileObj.id);
          /*
          $('.director input[type=hidden]').each(function(){
            alternative.debug($(this).attr('id') +': ' + $(this).val());
          })
          */
        }
    
      });
}

$(document).ready(function(){
  swfobject.embedSWF("/swf/video.swf", "logo", "380", "200", "9.0.0", "expressInstall.swf","",{"wmode":"transparent","allowFullScreen":"false", 'autoPlay' : 'false'});
  initUploads();
  $('.lightbox').fancybox();
  $('a[rel="external"]').attr('target', '_blank');
  $('#news-scroll').vTicker({
    speed:1500
  });
  
})

function addDirector($lang_dir){
  var $template = $('#director').clone(false).removeAttr('id');
  var $count = $('.director').length;
  $a = $('<div><span>' + $lang_dir + ' ' + ($count+1) + '</span> <a class="del" onclick="deleteDirector(this);return false;" href="javascript:;">x</a>');
  $a.insertBefore($template.find('label:first'));
  $template.appendTo($('#director').parent());
  //alternative.debug($count);
  $template.find('input').each(function(){
      $(this).attr('name', $(this).attr('name').replace(/\[0\]/, '[' + $count + ']'));
      if ($(this).attr('id')!='')
        $(this).attr('id', $(this).attr('id').replace(/0/,  $count));
      $(this).val('')
      $(this).removeAttr('checked');
  });
  $template.find('textarea').each(function(){
    $(this).attr('name', $(this).attr('name').replace(/\[0\]/, '[' + $count + ']'));
    $(this).val('');  
  })
  $template.find('span.error').text('');
  $template.find('img').attr('src','');
  $template.find('img').attr('id','img_pic_director_' + $count);
  $template.find('object').remove();
  $template.find('input[type=file]').attr('id','pic_director_' + $count);
  reIndexDirectors();
}

function deleteDirector(obj){
  $(obj).parent().parent().remove();
  reIndexDirectors();
}

function reIndexDirectors(){
  $i = 0;
  // remove uploadify
  $('.director_pic').unbind("uploadifySelect");

  // iterate through directors
  $('.director').each(function(){
    // Dir #n
    var $dirno = $(this).find('div>span'); 
    $dirno.text($dirno.text().replace(/(.*)\s(\d+)/g, '$1 ' + ($i+1)));
    // reindex
    $(this).find('input').each(function(){
      $(this).attr('name', $(this).attr('name').replace(/\[(\d+)\]/, '[' + $i + ']'));
      if ($(this).attr('id')!=''){
        // remove uploadify swf
        swfobject.removeSWF($(this).attr('id') + 'Uploader');
        $('#' + $(this).attr('id') + 'Queue').remove();
        $(this).attr('id', $(this).attr('id').replace(/(\d+)/, $i));
      }
    })
    $(this).find('textarea').each(function(){
      $(this).attr('name', $(this).attr('name').replace(/\[(\d+)\]/, '[' + $i + ']'));
    });
    $(this).find('img').each(function(){
      $(this).attr('id', $(this).attr('id').replace(/(\d+)/, $i));
    });
    // add uploadify
    var $id = 'pic_director_' + $i;
    attachUploadify($id);
    ++$i;
  });
}


function addProducer($lang_prod){
  var $template = $('#producer').clone(false).removeAttr('id');
  var $count = $('.producer').length;
  $a = $('<div><span>' + $lang_prod + ' ' + ($count+1) + '</span> <a class="del" onclick="deleteProducer(this);return false;" href="javascript:void(0);">x</a>');
  $a.insertBefore($template.find('label:first'));
  $template.appendTo($('#producer').parent());
  $template.find('input').each(function(){
      $(this).attr('name', $(this).attr('name').replace(/\[0\]/, '[' + $count + ']'));
      $(this).val('');
  });
  $template.find('span.error').text('');
  reIndexProducers();
}

function deleteProducer(obj){
  $(obj).parent().parent().remove();
  reIndexProducers();
}

function reIndexProducers(){
  var $i = 0;
  // iterate through producers
  $('.producer').each(function(){
    // producer #n
    var $prodno = $(this).find('div>span'); 
    $prodno.text($prodno.text().replace(/(.*)\s(\d+)/g, '$1 ' + ($i+1)));
    // reindex
    $(this).find('input').each(function(){
      $(this).attr('name', $(this).attr('name').replace(/\[(\d+)\]/, '[' + $i + ']'));
    })
    ++$i;
  });  
}

function copyCorrAddress(obj) {
  $(obj).parent().find('input[type="text"]').each(function(){
    var $name = $(this).attr('name').replace(/correspondence/, 'return');
    $('#ret_addr').find('input[name="' + $name + '"]').val($(this).val());
  })
}

alternative = {
  debug : function($data){
    //$('#debug').html($('#debug').html() + '<br />' + $data);
  },
  rmImage : function(obj){
    $(obj).prev('img').remove();
    $(obj).prev('input[type="hidden"]').remove();
    $(obj).remove();
    $had_alert = false;
    return false;    
  }
}


/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */  function print_r(x, max, sep, l) {

    l = l || 0;
    max = max || 10;
    sep = sep || ' ';

    if (l > max) {
      return "[WARNING: Too much recursion]\n";
    }

    var
    i,
    r = '',
    t = typeof x,
    tab = '';

    if (x === null) {
      r += "(null)\n";
    } else if (t == 'object') {
      l++;
      for (i = 0; i < l; i++) {
        tab += sep;
      }
      if (x && x.length) {
        t = 'array';
      }
      r += '(' + t + ") :\n";
      for (i in x) {
        try {
          r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
        } catch(e) {
          return "[ERROR: " + e + "]\n";
        }
      }
    } else {
      if (t == 'string') {
        if (x == '') {
          x = '(empty)';
        }
      }
      r += '(' + t + ') ' + x + "\n";
    }
    return r;
  };
  var_dump = print_r;



