var msie5 = (navigator.userAgent.indexOf('MSIE 5') != -1);
var msie = (navigator.userAgent.indexOf('MSIE') != -1);

//***********************************************************
// FCKEditor

var popup_editor_form = 'popup_fckeditor_form';
var width = 670;
var height = 580;

function popup_rte(input_id, label_edit) {
    var args, value;
    value = document.getElementById(input_id).value;
    args = '?input_id='+input_id+'&amp;label_edit='+escape(label_edit);
    str_window_features = 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,dependent=1,width=' + width + ',height=' + height;
    popup = window.open(popup_editor_form + args, input_id, str_window_features);
    if (!popup.opener) {
        popup.opener = window;
    }
    return false;
}


//************************************************************
// Folder content
var isSelected = false;

function toggleSelect(toggleSelectButton, selectAllText, deselectAllText) {
  formElements = toggleSelectButton.form.elements;

  if (isSelected) {
    for (i = 0; i < formElements.length; i++) {
      formElements[i].checked = false;
    }
    isSelected = false;
    toggleSelectButton.value = selectAllText;
  } else {
    for (i = 0; i < formElements.length; i++) {
      formElements[i].checked = true;
    }
    isSelected = true;
    toggleSelectButton.value = deselectAllText;
  }
}

//************************************************************
/**
 * Toggles an element's visibility.
 * Function to show tooltips.
 * If your element is a span, you must use inline display instead of block
 * XXX recognize div and span then automaticly choose the best display rule
 */
function toggleElementVisibility(id) {
  element = document.getElementById(id);
  if (element) {
    //window.alert(element.tagName)
    if (element.style.visibility == 'hidden') {
      element.style.visibility = 'visible';
      if (element.tagName == 'DIV') {
        element.style.display = 'block';
      } else if (element.tagName == 'SPAN') {
        element.style.display = 'inline';
      } else {
        element.style.display = 'block';
      }
    } else {
      element.style.visibility = 'hidden';
      element.style.display = 'none';
    }
  }
}

function showElement(show, id) {
  element = document.getElementById(id);
  if (element) {
    //window.alert(element.tagName)
    if (show) {
      element.style.visibility = 'visible';
      if (element.tagName in ['DIV', 'P']) {
        element.style.display = 'block';
      } else {
        element.style.display = 'inline';
      }
    } else {
      element.style.visibility = 'hidden';
      element.style.display = 'none';
    }
  }
}

//************************************************************
function trim(s) {
  if (s) {
    return s.replace(/^\s*|\s*$/g, "");
  }
  return "";
}

//************************************************************
function checkEmptySearch(formElem) {
  var query = trim(formElem.SearchableText.value);
  if (query != '') {
    formElem.SearchableText.value = query;
    return true;
  }
  formElem.SearchableText.value = query;
  formElem.SearchableText.focus();
  return false;
}

//************************************************************
/**
 * Sets focus on <input> elements that have a class attribute
 * containing the class 'focus'.
 * Examples:
 * <input type="text" id="username" name="__ac_name" class="focus"/>
 * <input type="text" id="searchableText" class="standalone giant focus"/>
 *
 * This function does not work on crappy MSIE5.0 and MSIE5.5.
 */
function setFocus() {
  if (msie5) {
    return false;
  }
  var elements = document.getElementsByTagName('input');
  for (var i = 0; i < elements.length; i++) {
    var nodeClass = elements[i].getAttributeNode('class');
    //alert("nodeClass = " + nodeClass);
    if (nodeClass) {
      var classes = nodeClass.value.split(' ');
      for (var j = 0; j < classes.length; j++) {
        if (classes[j] == 'focus') {
          elements[i].focus();
          return true;
        }
      }
    }
  }
}

/**
 * Validates that the input fields designated by the given ids are not empty.
 * It returns true if all the input fields are not empty, it returns false
 * otherwise.
 * Example:
 * <form onsubmit="return validateRequiredFields(['field1', 'field2'],
 * ['Title', 'Comments'], 'are empty while they are required fields.')">
 */
function validateRequiredFields(fieldIds, fieldLabels, informationText) {
  for (i = 0; i < fieldIds.length; i++) {
    element = document.getElementById(fieldIds[i]);
    if (element && !element.value) {
      window.alert("'" + fieldLabels[i] + "' " + informationText);
      return false;
    }
  }
  return true;
}

//************************************************************
function getSelectedRadio(buttonGroup) {
  if (buttonGroup[0]) {
    for (var i=0; i<buttonGroup.length; i++) {
      if (buttonGroup[i].checked) {
        return i
      }
    }
  } else {
    if (buttonGroup.checked) {return 0;}
  }
  return -1;
}

function getSelectedRadioValue(buttonGroup) {
  var i = getSelectedRadio(buttonGroup);
  if (i == -1) {
    return "";
  } else {
    if (buttonGroup[i]) {
    return buttonGroup[i].value;
    } else {
    return buttonGroup.value;
    }
  }
}

function getSelectedRadioId(buttonGroup) {
  var i = getSelectedRadio(buttonGroup);
  if (i == -1) {
    return "";
  } else {
    if (buttonGroup[i]) {
      return buttonGroup[i].id;
    } else {
      return buttonGroup.id;
    }
  }
}

/**
 * Return the label content corresponding to a radio selection
 */
function getSelectedRadioLabel(buttonGroup) {
  var id = getSelectedRadioId(buttonGroup);
  if (id == "") {
    return "";
  } else {
    for (var i=0; i<document.getElementsByTagName("label").length; i++) {
      var element_label = document.getElementsByTagName("label")[i];
      if (element_label.htmlFor == id) {
        return element_label.firstChild.nodeValue;
      }
    }
  }
}


//************************************************************
/*
    Used to highlight search terms
    from Geir Bækholt, adapted for CPS

 */
function highlightSearchTerm() {
  var query_elem = document.getElementById('searchGadget')
  if (! query_elem){
    return false
  }
  var query = query_elem.value
  // _robert_ ie 5 does not have decodeURI
  if (typeof decodeURI != 'undefined'){
    query = unescape(decodeURI(query)) // thanks, Casper
  }
  else {
    return false
  }
  if (query){
    queries = query.replace(/\+/g,' ').split(/\s+/)
    // make sure we start the right place and not higlight menuitems or breadcrumb
    searchresultnode = document.getElementById('searchResults')
    if (searchresultnode) {
      for (q=0;q<queries.length;q++) {
        // don't highlight reserved catalog search terms
        if (queries[q].toLowerCase() != 'not'
          && queries[q].toLowerCase() != 'and'
          && queries[q].toLowerCase() != 'or') {
          climb(searchresultnode,queries[q]);
        }
      }
    }
  }
}

function climb(node, word){
  // traverse childnodes
  if (! node){
    return false
  }
  if (node.hasChildNodes) {
    var i;
    for (i=0;i<node.childNodes.length;i++) {
      climb(node.childNodes[i],word);
    }
    if (node.nodeType == 3) {
      checkforhighlight(node, word);
      // check all textnodes. Feels inefficient, but works
    }
  }
}

function checkforhighlight(node,word) {
  ind = node.nodeValue.toLowerCase().indexOf(word.toLowerCase())
  if (ind != -1) {
    if (node.parentNode.className != "highlightedSearchTerm"){
      par = node.parentNode;
      contents = node.nodeValue;
      // make 3 shiny new nodes
      hiword = document.createElement("span");
      hiword.className = "highlightedSearchTerm";
      hiword.appendChild(document.createTextNode(contents.substr(ind,word.length)));
      par.insertBefore(document.createTextNode(contents.substr(0,ind)),node);
      par.insertBefore(hiword,node);
      par.insertBefore(document.createTextNode( contents.substr(ind+word.length)),node);
      par.removeChild(node);
    }
  }
}

/************************************************************
/**
 * searchLanguage widget functions
 * used to auto select languages checkbox/radio
 * cf CPSSchemas/skins/cps_schemas/widget_searchlanguage_render.pt
 */
function searchLanguageCheckSelected(languages, no_language, language) {
  var count=0;
  for (var i=0; i<languages.length; i++) {
    if (languages[i].checked) {
      count++;
    }
  }
  no_language.checked = (count <= 0);
  language.checked = (count > 0);
}

function searchLanguageClearSelected(languages) {
  for (i=0; i<languages.length; i++) {
    languages[i].checked = 0;
  }
}

function toggleLayers(more_block, more_items) {
  var objMoreBlock = document.getElementById(more_block).style;
  var objMoreItems = document.getElementById(more_items).style;
  if(objMoreBlock.display == "block")
    objMoreBlock.display = "none";
  if(objMoreItems.display == "none")
    objMoreItems.display = "block";
}

//-----------------------------------------------------------------------------
//Funtion previewPrint
//-----------------------------------------------------------------------------
function previewPrint()
{
if (navigator.appName  != 'Microsoft Internet Explorer') {
window.print();
}
else
{
document.body.insertAdjacentHTML('beforeEnd', '<OBJECT ID="nav" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
nav.ExecWB(7,1);
nav.outerHTML = "";
}
}


//-----------------------------------------------------------------------------
//Function rolloverMap
//-----------------------------------------------------------------------------
function rollOverMap(mapName, mapOver){
	document[mapName].src=mapOver;
}

//-----------------------------------------------------------------------------
//Function font control
//-----------------------------------------------------------------------------
function fontCtrl(action){

	if (!document.body.style.fontSize)  document.body.style.fontSize = '100%';

	if (action=='increase'){
		document.body.style.fontSize = parseInt(document.body.style.fontSize)+10+'%';
	}
	else if (action =='decrease'){
		document.body.style.fontSize = parseInt(document.body.style.fontSize)-10+'%';
	}
	else {
		alert("unknown action !");
	}
	return false
}

//-----------------------------------------------------------------------------
//Function utils
//-----------------------------------------------------------------------------

function openWindow(title, url, width, height){
    popup_title = 'popup'; // Avoid crashes in IE when title contains localized caracters or punctuation
    var w = window.open(url, popup_title, 'scrollbars=no, toolbar=no, location=no, menubar=no, statusbar=no, alwaysRaised=no, resizable=no, width='+width+', height='+height);
    w.focus();
    return false;
}

function openDocumentWindow(title, url, width, height){
    popup_title = 'popup'; // Avoid crashes in IE when title contains localized caracters or punctuation
    var w = window.open(url, popup_title, 'scrollbars=yes, resizable=yes, toolbar=no, location=no, menubar=no, statusbar=no, alwaysRaised=no, width='+width+', height='+height);
    w.focus();
    return false;
}

function updateDisplayedImage(target, image, album){
    var html = '<a href="'+image.url+'" onclick="return openWindow(\''+image.name+'\', \''+image.url+'\', '+width+', '+height+')"> <img src="'+image.src+'" alt="'+image.name+'" title="'+image.description+'"/></a><div class="legende">'+album+'</div>';
    target.innerHTML = html;
}

function addToFavorites(anchor){
    if (window.sidebar){
        window.sidebar.addPanel(anchor.getAttribute('title'), anchor.getAttribute('href'), "");
    }else if (window.external){
        window.external.AddFavorite(anchor.getAttribute('href'), anchor.getAttribute('title'));
    }
}

//-----------------------------------------------------------------------------
//Function rollover
//-----------------------------------------------------------------------------

function display_infos(e, text){
        var c = $('#curseur')
        var el = $(e)
        c.html(text);
        c[0].style.top = 515 + 'px'
        //c[0].style.top = (el.position().top + 480) + 'px'
        if (msie) {
	   c[0].style.left = 425 + 'px'
	   //c[0].style.left = (el.position().left + 230) + 'px'
	}else{
           //c[0].style.left = (el.position().left + 470) + 'px'
           c[0].style.left = 660 + 'px'
        }
	c.toggle();
}


function display_block(id){
    var e = document.getElementById(id);
    var  f = document.getElementById(id+'_li');
    e.style.display = "block";
    if (f.className == "last"){
	f.className = "open last";
    }
    else if (f.className == ""){
	f.className="open";    
    }

}

function hide_block(id){
    var e = document.getElementById(id);
    var  f = document.getElementById(id+'_li');    
    e.style.display = "none";
    if (f.className == "open last"){
	f.className = "last";
    }
    else if (f.className == "open"){
	f.className="";    
    }
}

/* Ou Sortir */
function openManif(x) {
	x=window.open(x.href, 'popupmanif', 'height=500, width=400, top=20, left=20, scrollbars=yes, resizable=yes, status=yes');
	x.focus();
	return false;
}


function openLinkPopup(field_id){
    window.document.getElementById("hidden_link_widget").value = field_id;
    var w = window.open('browse_server.html');
    w.opener = window;
    return false;
}


//-----------------------------------------------------------------------------
// Show or hide a collapsible pane
//-----------------------------------------------------------------------------
function toggleCollapsiblePane(pane_id){
	var contents = $("#" + pane_id);
	var icon = $("#icon_" + pane_id);
        contents.toggle();
        icon.toggleClass('collapsible_pane_icon_close collapsible_pane_icon_open');
}

//-----------------------------------------------------------------------------
// JQUERY FOR COUP DE POUCE BACKOFFICE
//-----------------------------------------------------------------------------
function add_entry(id, label){
    return function (){
        $('#entry_1').append('<li id="' + id + '"><input type="checkbox" checked="checked" name="categories.' + id + ':record"><span>' + label + '</span><button class="entry_edit" title="Modifier"></button><button class="entry_delete" title="Supprimer"></button></li>')
        $('#entry_1 li#' + id + ' button.entry_edit').click(jquery_coupdepouce_edit)
        $('#entry_1 li#' + id + ' button.entry_delete').clik(jquery_coupdepouce_delete_entry)
        return false;
    }
}

function replace_entry(node, id, label){
    return function (){
        if(label == undefined){
            label = node.find("input")[0].value
            $.ajax({
            type: "POST",
            url: "edit_entry",
            data: {'id': id,
                   'label': label},
            success: function(data){
                        node.html('<input type="checkbox" checked="checked" name="categories.' + id + ':record"><span>' + label + '</span><button class="entry_edit" title="Modifier"></button><button class="entry_delete" title="Supprimer"></button>')
                        $('#entry_1 li#' + id + ' button.entry_edit').click(jquery_coupdepouce_edit)
                        $('#entry_1 li#' + id + ' button.entry_delete').click(jquery_coupdepouce_delete_entry)
                     }
            });
        }else{
            node.html('<input type="checkbox" checked="checked" name="categories.' + id + ':record"><span>' + label + '</span><button class="entry_edit" title="Modifier"></button><button class="entry_delete" title="Supprimer"></button>')
            $('#entry_1 li#' + id + ' button.entry_edit').click(jquery_coupdepouce_edit)
            $('#entry_1 li#' + id + ' button.entry_delete').click(jquery_coupdepouce_delete_entry)
        }
        return false;
    }

}

var coupdepouce_edit_id;

function jquery_coupdepouce_edit(){
    coupdepouce_edit_id = $(this).parent("li")[0].id
    
    $('#dialog-form').dialog('open');

//    li = $(this).parent("li")
//    id = li[0].id
//    span = $(this).prev('span')
//    v = span.text();
//    $(this).parent('li').html('<input type="text" value="' + v + '"><button class="edit_validate"></button><button class="edit_cancel" title="Annuler"></button>');
//    $('#entry_1 li#' + id + ' button.edit_validate').click(replace_entry_1(li, id))
//    $('#entry_1 li#' + id + ' button.edit_cancel').click(replace_entry_1(li, id, v))
//    return false;
}

function jquery_coupdepouce_delete_entry(){
    if (confirm('Confirmation de la suppression de l\'entrée "' + $(this).parent("li").children("span").html() + '"?')){
        $.ajax({
            type: "POST",
            url: "delete_entry",
            data: {'id': $(this).parent("li")[0].id}
        });
        $(this).parent("li").remove();
    }
}

function jquery_coupdepouce_change_entry_enable(){
    if ($(this).parent("li").find("input")[0].checked == false){
        url = "disable_entry"
    }else{
        url = "enable_entry"
    }
    $.ajax({
        type: "POST",
        url: url,
        data: {'id': $(this).parent("li")[0].id}
    });
}

function jquery_coupdepouce() {
    $("#entry_1").sortable({placeholder: 'ui-state-highlight',
                            stop: function(event, ui){
                                    $.ajax({
                                        type: "POST",
                                        url: "set_entries_order",
                                        data: {'label_ordered': $(this).sortable('toArray').toString()}
                                    })
                                  }
                          });
    $("#entry_1").disableSelection();

    $("#add_entry_button").button().click(
    function(){
        label = document.getElementById('add_entry_input').value
        $.ajax({
            type: "POST",
            url: "add_entry",
            data: {'label': label},
            success: function(data){
                        $('#entry_1').append('<li id="' + data + '"><input type="checkbox" name="categories.' + data + ':record"><span>' + label + '</span><button class="entry_edit" title="Modifier"></button><button class="entry_delete" title="Supprimer"></button></li>')
                        $('#entry_1 li#' + data + ' button.entry_edit').click(jquery_coupdepouce_edit)
                        $('#entry_1 li#' + data + ' button.entry_delete').click(jquery_coupdepouce_delete_entry)
                        $('#entry_1 li#' + data + ' input').click(jquery_coupdepouce_change_entry_enable)
                     }
        });
        return false;
    })

    $("#entry_1 li button.entry_edit").click(jquery_coupdepouce_edit)
    $("#entry_1 li button.entry_delete").click(jquery_coupdepouce_delete_entry)

    $("#entry_1 li input").click(jquery_coupdepouce_change_entry_enable)
}




function init_coupdepouce_form() {
    var entry_1_title = $("#entry_1_title"),
        entry_2_enable_list_1 = $("#entry_2_enable_list_1"),
        entry_2_title_list_1 = $("#entry_2_title_list_1"),
        entry_2_list_1 = $("#entry_2_list_1"),
        entry_2_enable_list_2 = $("#entry_2_enable_list_2"),
        entry_2_title_list_2 = $("#entry_2_title_list_2"),
        entry_2_list_2 = $("#entry_2_list_2"),
        entry_2_enable_dates = $("#entry_2_enable_dates"),
//        entry_2_date_1 = $("#entry_2_date_1"),
//        entry_2_date_2 = $("#entry_2_date_2"),
        entry_3_enable_list = $("#entry_3_enable_list"),
        entry_3_list = $("#entry_3_list"),
        entry_3_enable_list = $("#entry_3_enable_list"),
        entry_3_list = $("#entry_3_list"),
        entry_4_enable_list = $("#entry_4_enable_list"),
        entry_4_list = $("#entry_4_list"),
        entry_4_extend = $("#entry_4_extend"),
        cities_selected = '',
        allFields = $([]).add(entry_1_title).add(entry_2_enable_list_1).add(entry_2_title_list_1),
        tips = $(".validateTips");

    function updateTips(t) {
            tips
                    .text(t)
                    .addClass('ui-state-highlight');
            setTimeout(function() {
                    tips.removeClass('ui-state-highlight', 1500);
            }, 500);
    }

    function checkLength(o,n,min,max) {

            if ( o.val().length > max || o.val().length < min ) {
                    o.addClass('ui-state-error');
                    updateTips("Length of " + n + " must be between "+min+" and "+max+".");
                    return false;
            } else {
                    return true;
            }

    }

    function checkRegexp(o,regexp,n) {

            if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass('ui-state-error');
                    updateTips(n);
                    return false;
            } else {
                    return true;
            }

    }

//    Array.prototype.map = function(fun){
//     var resultat =[] ;
//     for(var i=0; i< liste.length ; i++)
//        resultat.push(fun(liste[i])) ;
//
//     return resultat ;
//    }

    function jsBoolToZopeBool(b){
        if(b){
            return "True"
        }else{
            return "False"
        }
    }

    $("#dialog-form").dialog({
            autoOpen: false,
            height: 800,
            width: 600,
            modal: true,
            open: function(event, ui) {
                $.ajax({
                    type: "POST",
                    url: "get_entry_json",
                    dataType: "json",
                    data: {'id': coupdepouce_edit_id},
                    success: function(data){
                        var l = '';
                        entry_1_title.val('')
                        entry_2_list_1.val('')
                        entry_2_list_2.val('');
                        entry_2_enable_list_1.val('');
                        entry_2_enable_list_2.val('');
                        entry_2_title_list_1.val('');
                        entry_2_title_list_2.val('');
                        entry_2_enable_dates.val('');
//                        entry_2_date_1.val('');
//                        entry_2_date_2.val('');
                        entry_3_enable_list.val('');
                        entry_3_list.val('');
                        entry_4_enable_list.val('');
                        entry_4_list.val('');
                        entry_4_extend.val('')
                        $("#entry_2_enable_list_1").next().show();
                        $("#entry_2_enable_list_2").next().show();
//                        $("#entry_2_enable_dates").next().show();
                        $("#entry_3_enable_list").next().show();
                        $("#entry_4_enable_list").next().show();
                        $("#cities li").removeClass('ui-selected', '')

                        entry_1_title.val(data['label'])
                        l = '';
                        $.each(data['entry_2_list_1'], function(i, item){
                            l += item[1] + '\n'
                        })
                        entry_2_list_1.val(l)

                        l = '';
                        $.each(data['entry_2_list_2'], function(i, item){
                            l += item[1] + '\n'
                        })
                        entry_2_list_2.val(l);
                        entry_2_enable_list_1[0].checked = data['entry_2_enable_list_1'];
                        entry_2_enable_list_2[0].checked = data['entry_2_enable_list_2'];
                        entry_2_title_list_1.val(data['entry_2_title_list_1']);
                        entry_2_title_list_2.val(data['entry_2_title_list_2']);
                        entry_2_enable_dates[0].checked = data['entry_2_enable_dates'];
//                        entry_2_date_1.val(data['entry_2_date_1']);
//                        entry_2_date_2.val(data['entry_2_date_2']);
                        entry_3_enable_list[0].checked = data['entry_3_enable_list'];
                        
                        var e_3_l = '';
                        $.each(data['entry_3_list'], function(i, item){
                            e_3_l += item[1] + '\n'
                        })
                        entry_3_list.val(e_3_l);

                        entry_4_enable_list[0].checked = data['entry_4_enable_list'];
                        entry_4_extend[0].checked = data['entry_4_extend'];
                        $("#entry_2_enable_list_1:not(:checked)").next().hide();
                        $("#entry_2_enable_list_2:not(:checked)").next().hide();
//                        $("#entry_2_enable_dates:not(:checked)").next().hide();
                        $("#entry_3_enable_list:not(:checked)").next().hide();
                        $("#entry_4_enable_list:not(:checked)").next().hide();
                        l = eval(data['entry_4_list'])
                        $.each(l, function(i, item){
                            $("#cities li#" + item).addClass('ui-selected')
                        })
                    }
                });
            },
            buttons: {
                    'Valider': function() {
                            var bValid = true;
                            cities_selected = ''
                            $("#cities li.ui-selected", this).each(function(){
                                cities_selected = cities_selected + this.id + ','
                            });
                            allFields.removeClass('ui-state-error');

                            //bValid = bValid && checkRegexp(entry_1_title,/^[a-z]([0-9a-z_\ ])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
                            // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//                            bValid = bValid && checkRegexp(entry_2_enable_list_1,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
//                            bValid = bValid && checkRegexp(entry_2_title_list_1,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
                            d = $(this)
                            if (bValid) {
                                $.ajax({
                                    type: "POST",
                                    url: "edit_entry",
                                    data: {'id': coupdepouce_edit_id,
                                           'label': entry_1_title.val(),
                                           'entry_2_list_1': entry_2_list_1.val(),
                                           'entry_2_list_2': entry_2_list_2.val(),
                                           'entry_2_enable_list_1:boolean': jsBoolToZopeBool(entry_2_enable_list_1[0].checked),
                                           'entry_2_enable_list_2:boolean': jsBoolToZopeBool(entry_2_enable_list_2[0].checked),
                                           'entry_2_title_list_1': entry_2_title_list_1.val(),
                                           'entry_2_title_list_2': entry_2_title_list_2.val(),
                                           'entry_2_enable_dates:boolean': jsBoolToZopeBool(entry_2_enable_dates[0].checked),
//                                           'entry_2_date_1': entry_2_date_1.val(),
//                                           'entry_2_date_2': entry_2_date_2.val(),
                                           'entry_3_enable_list:boolean': jsBoolToZopeBool(entry_3_enable_list[0].checked),
                                           'entry_3_list': entry_3_list.val(),
                                           'entry_4_enable_list:boolean': jsBoolToZopeBool(entry_4_enable_list[0].checked),
                                           'entry_4_list': cities_selected,
                                           'entry_4_extend:boolean': jsBoolToZopeBool(entry_4_extend[0].checked)
                                    },
                                    success: function(data){
                                                $('#entry_1 li#' + coupdepouce_edit_id + ' span').text(entry_1_title.val())
                                                d.dialog('close');
                                             }
                                    });
                                    
                            }
                    },
                    'Annuler': function() {
                            $(this).dialog('close');
                    }
            },
            close: function() {
                    allFields.val('').removeClass('ui-state-error');
            }
    });

//    $.datepicker.setDefaults($.datepicker.regional['fr']);
//
//    $("#entry_2_date_1").datepicker();
//
//    $("#entry_2_date_2").datepicker();

    function jquery_toggle(){
        $(this).next().toggle('slow');
//        alert($(this)[0].checked)
//        $(this).parent("fieldset").visible = $(this).checked
    }

    $("#entry_2_enable_list_1").click(jquery_toggle);
    $("#entry_2_enable_list_2").click(jquery_toggle);
//    $("#entry_2_enable_dates").click(jquery_toggle);
    $("#entry_3_enable_list").click(jquery_toggle);
    $("#entry_4_enable_list").click(jquery_toggle);

    $("#cities li").click(function(){$(this).toggleClass('ui-selected')})

    $("#cities_select_all").click(function(){$("#cities li").addClass('ui-selected')})
    $("#cities_unselect_all").click(function(){$("#cities li").removeClass('ui-selected')})

//    $("#cities").selectable();
};


//function swap_video(){
//    return '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="460" height="306"><param name="src" value="http://mediatheque.ardeche.cda.com/%E0%20consulter/Vid%E9oth%E8que/Villages%20de%20caract%E8res/ailhon.mov"><param name="autoplay" value="false"><param name="controller" value="true"><embed type="video/quicktime" controller="true" autoplay="false" src="http://mediatheque.ardeche.cda.com/%E0%20consulter/Vid%E9oth%E8que/Villages%20de%20caract%E8res/ailhon.mov" width="460" height="306"></object>'
//}

function get_video_html(src){
    var a = src.split(".");
    var mimetype = a[(a.length-1)].split("?")[0]

    if(mimetype == 'mov'){
        return '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="460" height="306"><param name="src" value="' + src + '"><param name="autoplay" value="false"><param name="controller" value="true"><embed type="video/quicktime" controller="true" autoplay="true" src="' + src + '" width="460" height="306"></object>'
    }
    if(mimetype == 'wmv' || mimetype == 'wma' || mimetype == 'avi' || mimetype == 'mpg' || mimetype == 'mpeg' || mimetype == 'mp3' || mimetype == 'mp4'){
        return '<object classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" standby="Chargement..." type="application/x-oleobject" width="460" height="306"><param name="FileName" value="' + src + '"><param name="autoplay" value="true"><param name="autostart" value="true"><param name="showcontrol" value="true"><embed type="application/x-mplayer2" console="video" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" autoplay="true" showcontrol="true" autostart="true" src="' + src + '" width="460" height="306"></embed></object>'
    }
    if(mimetype == 'ra' || mimetype =='rm' || mimetype =='ram' || mimetype =='rv'){
        return '<object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" width="460" height="306"><param name="console" value="video"><param name="controls" value="All"><param name="autostart" value="true"><param name="src" value="' + src + '"><embed  type="audio/x-pn-realaudio-plugin" controls="All" console="video" autostart="true" src="' + src + '" width="460" height="306"></embed></object>'
    }
    if(mimetype == 'swf'){
        return '<object type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" data="' + src + '" width="460" height="306"><param name="movie" value="' + src + '" /><embed menu="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" src="' + src + '" width="460" height="306"></embed></object>'
    }
    if(mimetype == 'flv'){
        p = 'showfullscreen=False&showloading=False&showvolume=False&showplayer=False&phpstream=False&showtime=False&buffershowbg=False&autoload=1&shortcut=False&flv=' + src + '&height=306&width=460&srt=False&showmouse=False&showswitchsubtitles=False&showstop=False&loop=False&autoplay=1'
        return '<object type="application/x-shockwave-flash"classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" data="./player_flv.swf" width="460" height="306"><param name="movie" value="./player_flv.swf"><param name="FlashVars" value="' + p + '""><embed menu="false" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" src="./player_flv.swf" width="460" height="306" FlashVars="' + p + '"></embed></object>'
//        return '<object width="460" height="306"><param name="movie" value="http://www.youtube.com/v/XLAsM763qcY&amp;hl=fr_FR&amp;fs=1&amp;"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed src="http://www.youtube.com/v/XLAsM763qcY&amp;hl=fr_FR&amp;fs=1&amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="460" height="306"></object>'
    }
}


function resize_video_html(html){
    return html.replace(/width="\d+"/g, 'width="460"')
}

function clean_video_html(html){
    var m = html.match(/<object.+<\/object>/)
    if (m != null){
        return m[0]
    }

    return ''
}

function swap_video(html_video, title, duration, url, vid){
    swap_video_only(html_video);
    $('#video_title').html(title);
    if (duration.length > 0){
        $('#video_duration').html('Durée:<em>' + duration + '</em>');
    }else{
        $('#video_duration').html('');
    }
    document.getElementById('video_favorite').href = url;
    document.getElementById('video_share').href = 'send_postcard_video?vid=' + vid;
}

function swap_video_only(html_video){
    $('#video_slot').html(resize_video_html(clean_video_html(html_video)));
}

