function zeroPad(num,count)
{
  var numZeropad = num + '';
  while(numZeropad.length < count) {
    numZeropad = "0" + numZeropad;
  }
  return numZeropad;
}

function listenPerPageSelect() {
  $(".per_page_select").change(
    function() {
      var loc = document.location.href;
      var param = 'per_page=' + $(this).val();
      if (loc.indexOf('?') > 0) {
        loc = loc.replace(/per_page=[^&]+/, param);
        if (loc.indexOf('per_page=') == -1) {
          loc = loc + "&" + param;
        }
      } else {
        loc = loc + "?" + param;
      }
      document.location.href = loc;
    }
  );
}

/* ------------ makeElementSticky ------------
Make element stick to top while scrolling down.
To use, you will need:
    1. add class to element, for example, sticky
    2. call 'autocompleteSlug('.sticky')' when document were ready.
*/
function makeElementSticky(selector){
    $(selector).css({
        height:   $(selector).height(),
        position: 'absolute'
    });

    var parentTopOffset = $(selector).position().top ;
    var windowTopOffset = $(selector).offset().top ;
    adjustStickyElementTop();
    $(window).scroll(adjustStickyElementTop);

    function adjustStickyElementTop(){
        var topOffset = $(window).scrollTop()-windowTopOffset ;
        $(selector).css('top', (topOffset>0?topOffset:0)+parentTopOffset);
    }
}

/* ------------ autocompleteSlug ------------
To use autocompleteSlug, you will need:
    1. input with class '.slug_dest', where to input and update slug.
    2. call 'autocompleteSlug' when document were ready.

Optional:
    input with class '.slug_source' or '.primary_slug_source', representing the source 
    that slug will be autocomplete with.
    Priority:
        When input with '.primary_slug_source' is existing and displaying, its value will used first.
        Otherwise will use '.slug_source'.
*/
function autocompleteSlug(){
    //var requiredElementsExist = ($('.slug_dest').length == 1 && ($('.slug_source').length+$('.primary_slug_source').length) > 0);
    //if(!requiredElementsExist) throw("One or more required elements not exist: .slug_dest, .slug_source, .primary_slug_source");
    if(!($('.slug_dest').length == 1)) throw(".slug_dest not exist.");

    var enableAutocomplete = false;
    var strippedSlug = null ;

    // Autocomplete will not be enable in editing model.
    if($('.slug_dest').attr('value').length == 0){
        enableAutocomplete = true ;
        $(".slug_source").keyup(onSourceChanged);
        $(".primary_slug_source").keyup(onSourceChanged);
    }

    // When slug changed, its value will be update by stripped one.
    $(".slug_dest").change(function(){
        if( strippedSlug!=null && strippedSlug != $(this).attr('value') )
            enableAutocomplete = false ;
        stripAndUpdateSlug($(this).attr('value'));
    });

    function onSourceChanged(){
        // Detect wether to update slug or not.
        if(!enableAutocomplete) return ;
        var isPrimary = $(this).hasClass('primary_slug_source') ;
        if(isPrimary){
            var isHidden = $(this).parents('div:hidden').length > 0 ;
            if(isHidden) return ;
        }
        else{
            var hasPrimary = $('.primary_slug_source').length > 0 ;
            var primaryIsDisplaying = hasPrimary && $('.primary_slug_source').parents('div:hidden').length == 0 ;
            if(primaryIsDisplaying) return ;
        }
        stripAndUpdateSlug($(this).attr('value'));
    }

    function stripAndUpdateSlug(value) {
        if(value.length ==0) return ;
        $.ajax({
            url: "/admin/strip_slug",
            data: {slug: value},
            success: function(result){
                $('.slug_dest').attr('value', result);
                strippedSlug = result;
            }
        });
    }
}


/* ------------ Uploader ------------
 * 
 */ 
Uploader = function(opts) {
    this.ajaxData = {
        type: opts.type,
        name: opts.name,
        style: opts.style,
        authenticity_token: opts.token
    };
    this._uploading= false;
    
    var emptyFun = function(){} ;
    this.onOpen    = opts.handlers.onOpen    || emptyFun ;
    this.onSelect  = opts.handlers.onSelect  || emptyFun ;
    this.onUpload  = opts.handlers.onUpload  || emptyFun ;
    this.onFailure = opts.handlers.onFailure || emptyFun ;
    this.onSuccess = opts.handlers.onSuccess || emptyFun ;
    this.id = opts.id ;
};

Uploader.prototype = {
  open: function(){
    
    $('#ajaxUploadDiv').remove();
    this.assetUploader = this.createAssetUploader();
    // Fix ajaxUpload error under Safari 3.2.1
    this.get(".upload_button").unbind("click").click(function(){ $('#ajaxUploadInput').click(); });
    
    this.dialog  = this.createAndDisplayDialog();
    this.onOpen(arguments);
    this.notUploading();
    
    var uploader = this;
    this.get(".cancel").unbind("click").click(function(){ uploader.cancel(); return false; });
  },
  close: function(){
    $.modal.close();
  },
  upload: function(){
    var selectNothing = (this.assetUploader._input === null || this.assetUploader._input.value == "" );
    if(selectNothing){
      this.failure(uploaderMessages.errorPrefix+uploaderMessages.noImage);
      return ;
    }
    
    this._uploading = true ;
    this.onUpload();
    this.uploading();
    this.assetUploader.setData(this.ajaxData);
    this.assetUploader.submit();
    // make uploads not hang in Safari 
    if (/AppleWebKit|MSIE/.test(navigator.userAgent)) {
      $.ajax({ url:"/closeKeepAlive", async:false });
    }
  },
  success: function(response){
    this._uploading = false ;
    this.onSuccess(response);
  },
  failure: function(error){
    this._uploading = false ;
    this.notUploading();
    this.onFailure(error);
  },
  cancel: function(){
    if(!this._uploading) return;
    $("iframe[id^='ValumsAjaxUpload']").remove();
    this.failure(uploaderMessages.canceled);
  },
  uploading: function() {
    this.get(".loading, .cancel").show();
    this.get(".upload_button, .close").hide();
    this.get(".errors").text("");
  },
  notUploading: function(){
    this.get(".upload_button, .close").show();
    this.get(".cancel, .loading").hide();
    this.get(".file_name").text("選択なし");
  },
  get: function(selector){ return $(this.id+" "+selector); },
  
  createAndDisplayDialog: function() {
    var middle = ($(window).width()-$(this.id).width())/2 ;
    
    return $(this.id).modal({
      overlayCss: {backgroundColor:"#000"},
      position: ["0",middle],
      escClose:false,
      onOpen: function (dialog) { 
        // Slide down the dialog
     	  dialog.data.hide();
     	  dialog.overlay.fadeIn('fast');
     	  dialog.container.fadeIn('fast', function () { 
     	    dialog.data.slideDown('fast', function(){
     	      // Quick Fix: dialog disappear under chrome.
     	      // This happens if showing new element cause the dialog size changed.
     	      dialog.data.css("top","0px"); 
     	    }); 
     	  });
      },
      onClose: function (dialog) { 
        // Slide up the dialog
      	dialog.data.slideUp('fast', function(){
      	  dialog.overlay.fadeOut('fast', function () { $.modal.close(); });
      	});
      }
    });
  },
  createAssetUploader: function() {
    if(this.get('.upload_button').length==0) return ;
    
    var uploader = this ;
    return new AjaxUpload(this.get('.upload_button'), {
      action: '/admin/assets',
      name: 'asset',
      autoSubmit: false,
      responseType: 'json',
      onChange: function(file, extension) {
        uploader.get(".file_name").text(file);
        uploader.onSelect();
      },
      onSubmit: function(file, ext){
        if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext))){
          uploader.failure(uploaderMessages.errorPrefix+uploaderMessages.invalidFileType);
          return false;
        }
      },
      onComplete: function(file, response) {
        switch(response.result) {
          case 'success':
            uploader.success(response);
            break;
          case 'failure':
            uploader.failure(uploaderMessages.errorPrefix+response.errors.join("<br/>"));
            break;
        }
      }
    });
  }
};

// Example:  
//  $(".artworkImage").centerWithin("div.parent", 380);
$.fn.centerWithin = function(parentSelector, minHeight, maxHeight){
  var parent = $(this).parents(parentSelector);
  var img = $(this);
  
  if(img.height()<minHeight) {
    parent.height(minHeight);
    img.css("margin-top", (parent.height()-img.height())/2);
  }else if(maxHeight && img.height()>maxHeight) {
    img.css("margin-top", (maxHeight-img.height())/2);
  }
  // Use css to center image horizontally instead.
  //img.css("margin-left", (parent.width()-img.width())/2);  
};

/** ------------------------------------
/**  Live convert to  URL Title Function
/** -------------------------------------*/
to_url_title = function(origin)
       {
           var s1 = arguments[0] || "";
           var s2 = arguments[1] || "";
           var el = document.getElementById("url_title");
           if(s2 == ""){
               var return_text = live_url_title(document.getElementById(origin).value);}
           else{
               str1 = live_url_title(document.getElementById(s1).value);
               str2 = live_url_title(document.getElementById(s2).value);
               if(str1 == "")
               {
                 var return_text =  str2 ;
               }
               else if(str2 == "")
               {
                 var return_text = str1;
               }
               else
               {
                 var return_text = str1 + "-" + str2;
               }

           }
           el.value = "" + return_text;
}

to_url_title2 = function(origin, url_id, only_en)
       {
           if(origin == undefined){return;}
           var s1 = arguments[0] || "";
           var el = document.getElementById(url_id);
           if(el == null){ return;}
           var temp = document.getElementById(origin).value;
           if(temp == null){ return;}
           var return_text = live_url_title(temp,only_en);
           el.value = "" + return_text;
}

live_url_title = function(origin,only_en)
        {
            if(origin == undefined){return;}
            var defaultTitle = '';
            var NewText = origin;
            if (defaultTitle != '')
            {
                if (NewText.substr(0, defaultTitle.length) == defaultTitle)
                {
                    NewText = NewText.substr(defaultTitle.length);
                }
            }

            NewText = NewText.toLowerCase();
            var separator = "-";
            NewText = NewText.replace(/\_/g, separator);

            // Foreign Character Attempt
            var table ={
               '223':'ss','224':'a','225':'a','226':'a','229':'a','227':'ae','230':'ae','228':'ae',
               '231':'c','232':'e','233':'e','234':'e','235':'e','236':'i','237':'i','238':'i',
               '239':'i','241':'n','242':'o','243':'o','244':'o','245':'o','246':'oe','249':'u',
               '250':'u','251':'u','252':'ue','255':'y','257':'aa','269':'ch','275':'ee','291':'gj',
               '299':'ii','311':'kj','316':'lj','326':'nj','353':'sh','363':'uu','382':'zh','256':'aa',
               '268':'ch','274':'ee','290':'gj', '298':'ii','310':'kj','315':'lj','325':'nj','352':'sh',
               '362':'uu','381':'zh'
            }

            NewText = NewText.replace('/<(.*?)>/g', '');
            NewText = NewText.replace('/\�\d+\;/g', '');
            NewText = NewText.replace('/\&\#\d+?\;/g', '');
            NewText = NewText.replace('/\&\S+?\;/g','');
            NewText = NewText.replace(/['\"\?\.\!*$\#@%;:,=\(\)\[\]]/g,'');      //'
            NewText = NewText.replace(/\s+/g, separator);
            NewText = NewText.replace(/\//g, separator);
            if(only_en) NewText = NewText.replace(/[^a-z0-9-_]/g,''); 
            NewText = NewText.replace(/\+/g, separator);
            NewText = NewText.replace(/[-_]+/g, separator);
            NewText = NewText.replace(/\&/g,'');
            NewText = NewText.replace(/-$/g,'');
            NewText = NewText.replace(/_$/g,'');
            NewText = NewText.replace(/^_/g,'');
            NewText = NewText.replace(/^-/g,'');

            return NewText;
          }




/* Remove picture area.( display at banner and artwork page. )  */
function removeAssetPictureArea(){
  var parent = $(this).parents(".formChoosePictureContainer") ;
  var superParent = $(this).parents(".formChoosePicture");
  if (superParent.find("li.asset:not(.removed)").length == 1) {
    alert("Sorry, could not remove last one uploader!");
    return false;
  }
  if (!confirm("Are you sure?")) {
    return false;
  }
  if( parent.attr("new") == "true" ){
    // If it is new or tmp, then remove from dom.
    $(this).parents('.asset:first').remove();
  }else{
    // else send mark _delete field to send to server.
    parent.find("input[type='checkbox']").attr("checked","true");
    $(this).parents('.asset:first').hide().addClass("removed");
  }
  return false;
}