var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;

function trim(stringToTrim) {
  if (stringToTrim) {
  	return stringToTrim.replace(/^\s+|\s+$/g,"");
  }
  return '';
}

function ltrim(stringToTrim) {
  if (stringToTrim) {
	  return stringToTrim.replace(/^\s+/,"");
  }
  return '';
}

function rtrim(stringToTrim) {
  if (stringToTrim) {
	  return stringToTrim.replace(/\s+$/,"");
  }
  return '';
}

function padl(n, totalDigits) { 
  n = n.toString(); 
  var pd = ''; 
  if (totalDigits > n.length) { 
    for (i=0; i < (totalDigits-n.length); i++) { 
      pd += '0'; 
    } 
  } 
  return pd + n.toString(); 
} 

function jsddm_open() {
  jsddm_canceltimer();
  jsddm_close();
  ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function jsddm_close() {
  if (ddmenuitem) {
    ddmenuitem.css('visibility', 'hidden');
  }
}

function jsddm_timer() {
  closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() { 
  if (closetimer) {
    window.clearTimeout(closetimer);
    closetimer = null;
  }
}

$.extend({
  loadMenu: function(callback) {        
    $('#jsddm > li').bind('mouseover', jsddm_open);
    $('#jsddm > li').bind('mouseout',  jsddm_timer);

    document.onclick = jsddm_close;
  },

  initialize: function(callback) {        
    $('input:button,input:submit,button').button();
    $('input:checkbox,input:radio,input:file').uniform();  		
    $('.tabs').tabs();
    $('.overlay-horizontal,.image-overlay-horizontal').draggable();
    
    $.uniformDataGrid();
    
    /*    
    $('#menu span.separator').hover(
      function () {
        var index = $(this).index();
        $('div.dynamic-menu div').not(':eq(' + index + ')').hide();
        $('div.dynamic-menu div:eq(' + index + ')').show();                    
      },
      function () {}
    );    
        
    $('#menu-wrapper').mouseleave(
      function () {          
        var index = $('#menu span.selected').parent().index();
        if (index == -1) {
          $('div.dynamic-menu div').delay(800).hide('fast');
        }
        else {            
          $('div.dynamic-menu div').not(':eq(' + index + ')').hide();
          $('div.dynamic-menu div:eq(' + index + ')').show();
        }
      }
    );    
    */
    	  
		$('#inProgress').button({
		  icons: {primary: 'ui-icon-in-progress'}
		});  		
	  	  
	  $('#internalReview').button({
		  icons: {primary: 'ui-icon-internal-review'}
		});  		
	  	  
		$('#clientReview').button({
		  icons: {primary: 'ui-icon-client-review'}
		});  		
	  	  
		$('#published').button({
		  icons: {primary: 'ui-icon-published'}
		});  		
	  	     
    try {	    
		  $('#questions').sortable({
		    placeholder: 'question-state-highlight',
		    revert: 200,
		    distance: 15,
		    update: function (event, ui) {            
		      var id = $('#surveyTemplateId').val();
		      var parms = $.getParmsFromArray('questions', $(this).sortable('toArray'));
		      var url = '../SortQuestions/' + id + parms;		        
          $.postAction(url, 'results');
		    }
		  });
		  $("#questions").disableSelection();	    
    }
    catch (err) {
      /*this.options is undefined*/
    }
	  
    var sandbox = $('#sandbox');
    if (sandbox.length > 0) {
      $.resizeSandbox();
      $(window).resize($.resizeSandbox);
    }

    try {	    
		  $('#sortedList').sortable({
		    placeholder: 'sorted-list-highlight',
		    revert: 200,
        opacity: 0.6,
        distance: 15,      
        handle: '.header',      
		    update: function (event, ui) {
          var url = $('#sortUrl').val() + '?item=' + ui.item.attr('id') + '&sequence=' + ui.item.index();
          $.ajax({url: url, type: 'POST'});
		    }
		  });
		  //$("#sortedList").disableSelection();	    
    }
    catch (err) {
      /*this.options is undefined*/
    }    

    if (callback) {
      callback();
    }
  }
});

// datagrid
$.extend({
  uniformDataGrid: function() {  
    $('table.datagrid td.checkbox div.checker').each(function() {      
      $(this).bind('click', function() {
        $(this).parentsUntil('div').find('tr.header th.checkbox input[type="checkbox"]').each(function() {            
          $.uniform.update($(this));
        });
      });
    });

    $('table.datagrid tr.header th.checkbox div.checker').each(function() {      
      $(this).bind('click', function() {
        $(this).parentsUntil('div').find('td.checkbox input[type="checkbox"]').each(function() {            
          $.uniform.update($(this));          
        });        
      });
    });    
  }
});

// details view toggle
$.extend({
  toggleView: function(element, id, expand, collapse) {
    var anchor = $(element);
    var image = $('img', anchor);
    var match = /\/expand.png$/.exec(image.attr('src')); 
    if (match == '/expand.png') {
      image.attr('src', collapse);
      $('#' + id + ' .collapsible').fadeIn('fast');
    }
    else {
      image.attr('src', expand);
      $('#' + id + ' .collapsible').hide();
    }    
    return false; 
  }
});

// upload files
$.extend({
  removeFile: function(element, index) {    
    $(element).parent().parent().find('.uploader').remove();
    $(element).parent().parent().children().first().append('<input id="file' + index + '" type="file" name="files" />');    
    $(element).parent().parent().children().first().children().first().uniform();    
  }
});

// async posts
$.extend({
  postAction: function(url, updateTargetId, callback) {
    Sys.Mvc.MvcHelpers._asyncRequest(url, 'post', '', null, {insertionMode: Sys.Mvc.InsertionMode.replace, loadingElementId: 'loader', updateTargetId: updateTargetId, onSuccess: function() {$.initialize(callback);}});
  }, 

  postActionWithFade: function(url, updateTargetId, callback) {
    $('#' + updateTargetId).fadeOut('fast', function() {Sys.Mvc.MvcHelpers._asyncRequest(url, 'post', '', null, {insertionMode: Sys.Mvc.InsertionMode.replace, loadingElementId: 'loader', updateTargetId: updateTargetId, onSuccess: function() {$.initialize(callback); $('#' + updateTargetId).fadeIn('fast');}});});
  }, 

  postActionWithFadeIn: function(url, updateTargetId, callback) {
    $('#' + updateTargetId).hide(); Sys.Mvc.MvcHelpers._asyncRequest(url, 'post', '', null, {insertionMode: Sys.Mvc.InsertionMode.replace, loadingElementId: 'loader', updateTargetId: updateTargetId, onSuccess: function() {$.initialize(callback); $('#' + updateTargetId).fadeIn('fast');}});
  },

  postActionWithEditor: function(url, imageListUrl, updateTargetId, property, callback) {  
    Sys.Mvc.MvcHelpers._asyncRequest(url, 'post', '', null, {insertionMode: Sys.Mvc.InsertionMode.replace, loadingElementId: 'loader', updateTargetId: updateTargetId, onSuccess: function() {$.initialize(callback); $.loadEditor(property, imageListUrl);}});
  }
});

// sandbox
$.extend({
  resizeSandbox: function() {  
    var sandbox = $('#sandbox');
    sandbox.width($(document).width() - 228);
    sandbox.height(Math.max($(window).height() - 317, 300));
  }
});

// questions
$.extend({
  updateQuestions: function(id) {    
    if ($('#questionAddSuccess').val() == '1') {
      var url = '../UpdateQuestions/' + id;
      $.postActionWithFadeIn(url, 'questionRepeater');
    }
  },

  deleteQuestion: function(element, url, updateTargetId) {
    var button = $(element);
    var exp = /\d+/;
    var id = exp.exec(button.attr('id'));
    $('#question_' + id).remove();
    $.postAction(url, updateTargetId);    
  },

  getParmsFromArray: function(name, array) {
    var parms = '';
    var start = true;
    var exp = /\d+/;
    $.each(array, function(index, value) {      
      var id = exp.exec(value);      
      if (id) {
        if (start) {
          parms += ('?' + name + '=' + id);
          start = false;
        }
        else {
          parms += ('&' + name + '=' + id);
        }		     
      }   
    });
    return parms;		      
  }
});

// resources
$.extend({
  loadResources: function(id) {
    var url = '../ResourcesDataGrid/' + id;
    $.postAction(url, 'resources');
  }
});

// generic records
$.extend({
  addRecord: function(name, deleteImage, upImage, downImage) { 
    var element = $('#newRecord');
    var value = $('<div/>').text(element.val()).html();
    value = trim(value);

    if (!value) {
      return;
    }
    
    $('#records').append($('<tr><th></th><td><input name="' + name + '" type="text" maxlength="255" style="width: 350px; vertical-align: middle;" value="' + value + '" /> <img src="' + upImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.swapUp(this);" /> <img src="' + downImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.swapDown(this);" /> <img src="' + deleteImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.removeRecord(this);" /></td></tr>'));
    element.val('');       
  },

  removeRecord: function(element) { 
    $(element).parent().parent().remove();
  }, 

  swapUp: function(element) {     
    if ($(element).parent().parent().prev().length == 0) {
      return;
    }    

    var current = $(element).parent().parent();
    var to = $(element).parent().parent().prev();
     
    current.insertBefore(to);    
  },

  swapDown: function(element) {    
    if ($(element).parent().parent().next().length == 0) {
      return;
    }    

    var current = $(element).parent().parent();
    var to = $(element).parent().parent().next();
     
    current.insertAfter(to);     
  }
});

// dashboard
$.extend({
  toggleGroup: function(element) {    
    var modeElement = $(element);
    var groupElement = modeElement.parent().find('input');
    
    if (modeElement.val() == 'iterate') {
      groupElement.removeAttr('readonly');      
    }
    else {      
      groupElement.val('');
      groupElement.attr('readonly', 'readonly');      
    }
  },

  addSurvey: function(deleteImage, upImage, downImage) { 
    var surveyElement = $('#survey');
    var modeElement = $('#mode');
    var groupElement = $('#group');
    
    if (!surveyElement.val() || !modeElement.val()) {
      return;
    }

    $('#surveys').append($('<tr><th></th><td id="currentSurvey"></td></tr>'));
    var current = $('#currentSurvey');

    var surveyClone = surveyElement.clone().val(surveyElement.val()).removeAttr('id').attr('name', 'surveys');
    surveyClone.find("option[value='']").remove();
    current.append(surveyClone);
    current.append(' ');
    
    var modeClone = modeElement.clone().val(modeElement.val()).removeAttr('id').attr('name', 'modes');    
    modeClone.find("option[value='']").remove();
    current.append(modeClone);
    current.append(' ');
    
    groupElement.clone().val(groupElement.val()).removeAttr('id').attr('name', 'groups').appendTo(current);
    current.append(' ');
    current.append('<img src="' + upImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.swapUp(this);" /> <img src="' + downImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.swapDown(this);" /> <img src="' + deleteImage + '" style="vertical-align: middle; cursor: pointer;" onclick="$.removeRecord(this);" />');
    current.removeAttr('id');
        
    surveyElement.val('');
    modeElement.val('');
    groupElement.val('');
    groupElement.attr('readonly', 'readonly');
  }
});

// editor
$.extend({
  loadEditor: function(id, imageListUrl) {   
    $('#' + id).tinymce({
      // General options
      theme: "advanced",
      plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
 
      // Theme options
      theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
      theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
      theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
      theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
      theme_advanced_toolbar_location: "top",
      theme_advanced_toolbar_align: "left",    
      theme_advanced_statusbar_location: "bottom",
      theme_advanced_resizing: true,
      
      // Example content CSS (should be your site CSS)
      //content_css: "/wgxmvc/resources/styles/main.css",
 
      // Drop lists for link/image/media/template dialogs
      //template_external_list_url: "lists/template_list.js",
      //external_link_list_url: "lists/link_list.js",
      external_image_list_url: imageListUrl,
      relative_urls: false

      //media_external_list_url: "lists/media_list.js",
 
      // Replace values for the template plugin
      //template_replace_values : {
      //  username: "Some User",
      //  staffid: "991234"
      //}
    });    
  }
});

function updateLinkText(id) {  
  var val = $('#' + id + ' .link-text-value').html();
  if (val) {
    $('#' + id + ' .link-text').html(val);
  }
}
