/**
* Globals
*/
var URL_POSTS = "service.php?type=post";
var URL_LOCATIONS = "service.php?type=location";
var URL_PROFILE = "service.php?type=profile";
var URL_TRANSLATION = "service.php?type=translation";

/**
* Post Class
*/
function Post(id, type, subtype, text, author, html, expandedHtml, locationlat, locationlon){
    this.id = id;
    this.type = type;
    this.subtype = subtype;
    this.text = text;
    this.author = author;
    this.locationlat = locationlat;
    this.locationlon = locationlon;
    this.html = html;
    this.expandedHtml = expandedHtml;
    this.googleMarker = null;
    this.visible = true;
    this.relations = null;
}


/**
* Changes the font size depending on whether an input field has more English or Arabic characters.
* This is needed because Arabic text appears smaller than English text of the same font size. This
* method assumes that there's an 'english' class in the Arabic css (smaller font size than the default
* font for Arabic UI) and an 'arabic' class in the English css (larger font size than the default 
* used for the English UI). 
*/
function adjustFontSize(id, uiLang, size, rows){
  var inputElement = document.getElementById(id);
  var text = inputElement.value;
  
  if (text != null && text.length > 10){
    var arCount = 0;
    var enCount = 0;
    
    //Iterate through the word and count number of English and Arabic characters
    for (var i=0; i<text.length; i++){
      if (detectLanguage(text.charAt(i))=='ar'){
        arCount++;
      } else {
        enCount++
      }
    }
    
    if (uiLang == 'ar'){
      if (enCount > arCount){
        //If in the Arabic UI, and there's more English than Arabic, change the font size
        setElementClass(inputElement,"english");
        
        //But keep the input field to same size proportions
        if (inputElement.nodeName=='TEXTAREA'){
          inputElement.setAttribute("cols",size*1.16);
          inputElement.setAttribute("rows",rows*1.30);
        } else if (inputElement.nodeName=='INPUT'){
          inputElement.setAttribute("size",size*1.17);
        }
      } else {
        //If in the Arabic UI, and there's more Arabic text, keep the original font size
        setElementClass(inputElement,"");
        
        //And keep the input field to same size proportions
        if (inputElement.nodeName=='TEXTAREA'){
          inputElement.setAttribute("cols",size);
          inputElement.setAttribute("rows",rows);
        } else if (inputElement.nodeName=='INPUT'){
          inputElement.setAttribute("size",size);
        }
      }
      
    } else if (uiLang == 'en'){
      if (arCount > enCount){
        //If in the English UI, and there's more Arabic than English, change the font size
        setElementClass(inputElement,"arabic");
        
        //But keep the input field to same size proportions
        if (inputElement.nodeName=='TEXTAREA'){
          inputElement.setAttribute("cols",size*0.755);
          inputElement.setAttribute("rows",rows*0.765);
        } else if (inputElement.nodeName=='INPUT'){
          inputElement.setAttribute("size",size*0.855);
        }
      } else {
        //If in the English UI, and there's more English text, keep the original font size
        setElementClass(inputElement,"");
        
        //And keep the input field to same size proportions
        if (inputElement.nodeName=='TEXTAREA'){
          inputElement.setAttribute("cols",size);
          inputElement.setAttribute("rows",rows);
        } else if (inputElement.nodeName=='INPUT'){
          inputElement.setAttribute("size",size);
        }
      }
    }
  }
}

/**
* This method does the same thing as adjustFontSize() but for the improved translation textarea, which 
* requires slightly different formatting
*/
function adjustTranslationSize(id, uiLang){
  var inputElement = document.getElementById(id);
  var text = inputElement.value;
  var currentClass = inputElement.getAttribute('class');
  
  if (text != null && text.length > 10){
    var arCount = 0;
    var enCount = 0;
    
    //Iterate through the word and count number of English and Arabic characters
    for (var i=0; i<text.length; i++){
      if (detectLanguage(text.charAt(i))=='ar'){
        arCount++;
      } else {
        enCount++
      }
    }
    
    if (enCount > arCount && currentClass=="arabic"){
      //If currently, the font is for Arabic text, but there's more English than Arabic text, switch to English font
      var transBoxElement = document.getElementById('box');
      //TODO: styling below should be in css class
      transBoxElement.setAttribute('style','position: absolute; width: 370px; height: 250px; z-index: 99; left: 455px; top: 271.5px;');
      setElementClass(inputElement,"english");
      
    } else if (arCount > enCount && currentClass=="english"){
      //If currently, the font is for English text, but there's more Arabic than English text, switch to Arabic font
      var transBoxElement = document.getElementById('box');
      //TODO: styling below should be in css class
      transBoxElement.setAttribute('style','position: absolute; width: 487px; height: 329px; z-index: 99; left: 338px; top: 271.5px;');
      setElementClass(inputElement,"arabic");
    }
  }
}

/**
* Determines the language the text has been typed in, based on its ASCII code.
*/
function detectLanguage(text){
  var ascii = text.charCodeAt(0);
  
  if (ascii>126){
    return 'ar';
  } else {
    return 'en';
  }
}

//TODO rename to clearDefaultFieldText + rename other methods clearDefaultXXX
/**
* Clears the default text of a field.
*/
function clearField(id, defaultText){
  var fieldElement = document.getElementById(id);
  if (fieldElement.value == defaultText){ 
    fieldElement.value = "";
  }
}

/**
* Clears the default text of the search field.
*/
function clearSearchField(){
  clearField("search-field",default_text_search); 
}

/**
* Clears the default text of the title field.
*/
function clearTitle(){
  clearField("add_post_title",default_title); 
}

/**
* Clears the default text of the URL field.
*/
function clearURL(){
  clearField("url",default_url); 
}

/**
* Clears the default text of the event search field.
*/
function clearEventSearch(){
  clearField("event_searchterm",default_event_search);
}

/**
* Clears the default text of the invite email field.
*/
function clearInviteEmail(){
  clearField("invite_email",default_invite_email);
}

/**
* Clears the default text of the person search field.
*/
function clearPersonSearch(){
  clearField("nameSuggest",default_person_search);
}

/**
* Clears the default text of a comment box
*/
function clearPostBody(postid){
  if (postid!=null & postid!=""){
    clearField("add_post_text_"+postid,default_post_body);
  } else {
    clearField("reply_to_main",default_post_body);
  }
}

/**
* Clears the default text of a location field
*/
function clearLocation(){
  clearField("add_post_location",default_text_location);
}

/**
* Clears the text in the location field
*/
function clearPostLocation(){ 
  var postLocationSearchElement = document.getElementById("add_post_location");
  
  if(postLocationSearchElement!=null){
    postLocationSearchElement.value = "";
  }
}

/**
* Clears the default text of a media location field
*/
function clearMediaLocation(){
  clearField("addmedia_location",default_text_location);
}

//TODO widgetapi.postListSendQueuedData
function hideProgressIcon(){
  var progressBarDiv = document.getElementById("progress-bar"); 
  if (progressBarDiv==null){
    progressBarDiv = document.getElementById("narrow-progress-bar");  
  }
  
  if(progressBarDiv != null){
    progressBarDiv.style.visibility = "hidden";
  }
}

//TODO duplicate method signature in ajax.js
function sendData(url, data, callbackFunction){
  var xmlDocSub;

  if (typeof window.ActiveXObject != 'undefined' ) {
    xmlDocSub = new ActiveXObject("Microsoft.XMLHTTP");
    xmlDocSub.onreadystatechange = function(){
      if(xmlDocSub.readyState == 4) {
        callbackFunction(xmlDocSub.responseXML);
      }
        }        
    } 
    else {
        xmlDocSub = new XMLHttpRequest();
        xmlDocSub.onload = function(){
          if(xmlDocSub.readyState == 4) {
            callbackFunction(xmlDocSub.responseXML);
          }
        }        
    }
    xmlDocSub.open("POST",url,true);
    xmlDocSub.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xmlDocSub.send(data);
}

//TODO duplicate method signature in ajax.js
function sendDataReplaceHtml(url, data, containerelement, callbackFunction){
  var htmlDoc = null;

  if (typeof window.ActiveXObject != 'undefined' ) {
    htmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
    htmlDoc.onreadystatechange = function(){
      if(htmlDoc.readyState == 4) {
        if (containerelement!=null) {
          containerelement.innerHTML = htmlDoc.responseText;
        }
        if(callbackFunction != null){
          callbackFunction();
        }
      }
        }        
    } 
    else {
        htmlDoc = new XMLHttpRequest();
        htmlDoc.onload = function(){
          if(htmlDoc.readyState == 4) {
            if (containerelement!=null) {
          containerelement.innerHTML = htmlDoc.responseText;
        }
            if(callbackFunction != null){
          callbackFunction();
        }
          }
          
        }        
    }
    htmlDoc.open("POST",url,true);
    htmlDoc.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    htmlDoc.send(data);
}

/**
* Creates an instance of the tool used to autocomplete place names if one does not exist already.
*/
var placeNameSuggest;
function initialisePlaceNameSuggest() {
  if (!placeNameSuggest) {
    placeNameSuggest = new Ajax.Autocompleter(
      "add_post_location",
      "placeNameSuggestResults",
      URL_LOCATIONS + "&action=lookup",
      {
        paramName:  "location_search",
        indicator:  'placeNameSuggestIndicator',
        afterUpdateElement : setSelectedLocationLatLong
      });
    var results = document.getElementById("placeNameSuggestResults");
    setElementClass(results, 'suggestResults');
  }
}

/**
* Creates an instance of the tool used to autocomplete media place names if one does not exist already.
*/
var placeNameMediaSuggest;
function initialiseMediaPlaceNameSuggest() {
  if (!placeNameMediaSuggest) {
    placeNameMediaSuggest = new Ajax.Autocompleter(
      "addmedia_location",
      "placeNameMediaSuggestResults",
      URL_LOCATIONS + "&action=lookup",
      {
        paramName:  "location_search",
        indicator:  'placeNameMediaSuggestIndicator',
        afterUpdateElement : setSelectedMediaLocationLatLong
      });
    var results = document.getElementById("placeNameMediaSuggestResults");
    setElementClass(results, 'suggestResults');
  }
}

/**
* Creates an instance of the tool used to autocomplete event names if one does not exist already.
*/
var eventSuggest;
function initialiseEventSuggest(postId){
  if(eventSuggest == null){
    eventSuggest = new Ajax.Autocompleter(
      "event_searchterm",
      "eventSuggestResults",
      URL_POSTS + "&action=eventsearch",
      {
      paramName: "event_searchterm",
      indicator: "eventSuggestIndicator",
      afterUpdateElement: setSelectedEvent
      }
    );
  }
  var results = document.getElementById("eventSuggestResults");
  setElementClass(results, 'suggestResults');
}

/**
* When a location is selected, the lat long is set
*/
function setSelectedLocationLatLong(placeNameTextField, resultListElement) {
  var latLongField = document.getElementById('location_latlon');
  latLongField.value = resultListElement.id;
}

/**
* When a media location is selected, the lat long is set
*/
function setSelectedMediaLocationLatLong(placeNameTextField, resultListElement) {
  var latLongField = document.getElementById('media_location_latlon');
  latLongField.value = resultListElement.id;
}

/**
* When an event is selected, the ID is set
*/
function setSelectedEvent(placeNameTextField, resultListElement) {
  var eventIdField = document.getElementById('event_select_id');
  eventIdField.value = resultListElement.id;
}

/**
* Browser-safe method which sets the css class for an HTML element. 
*/
function setElementClass(element, className){
  if(element != null){
    element.setAttribute("class", className);
    element.setAttribute("className", className);
  }
}

/**
* Carries out a search based on the search term entered by the user
*/
function doSearch(){
  var searchElement = document.getElementById("search-field");
  
  if(searchElement != null && searchElement.value != null && searchElement.value != ""){
    var searchTerm = searchElement.value;
    window.location = "index.php?page=search&filterbytype=all&s="+searchTerm;
  }
}

/**
* Submits a form when the user presses Enter
*/
function submitOnEnter(f, e, onComplete){
  var keycode;
    if(window.event) {
        keycode = window.event.keyCode;
    } else if (e.which) {
        keycode = e.which;
    } else {
        // unknown browser give up.
        return true;
    }
    if (keycode == 13) {
        onComplete();
    }
    return true;
}

/**
* Validates a URL
*/
function validateURL(url){
  var urlErrorElement = document.getElementById("invalid-url");
	if( !urlErrorElement )
	 document.getElementById("comment_tab_url");

  //Not empty
  if(url=="" || url==null || url=='URL'){
    urlErrorElement.style.display = "block";
    return null;
  }

  //Has .
  if (url.indexOf('.')<0){
    urlErrorElement.style.display = "block";
    return null;
  }
  
  //No spaces
  if (url.indexOf(' ')>-1){
    urlErrorElement.style.display = "block";
    return null;
  }
  
  //Starts with http or https
  if ((url.substring(0,7)!='http://') && url.substring(0,8)!='https://'){
    url = 'http://'+url;
  }
  urlErrorElement.style.display = "none";
  return url;
}

/**
* Shows the manage translation pop up window.
*/
function manageTranslation (postid, referer) {
  var url;
  
  //If translating message, set 'referer' so user can go back to inbox/sent items
  if (referer!=null && referer!=""){
    url = 'index.php?page=managetranslation&post_id='+postid+'&referer='+referer;
  } 
  else {
    var forward = escape("index.php?page=managetranslation&post_id="+postid); 
    url = 'index.php?page=managetranslation&post_id='+postid+"&forward="+forward;
  }
  window.open(url);
  
}

/*
* When Improve Translation window is closed, the parent window is refreshed
*/ 
function refreshParent(url) {
  
  if(url == null || url == ""){
    return;
  }
  
  var target = url;
  
  //If there's a '#post' at the end of the URL, remove it
  if (target.indexOf('#post') != null && target.indexOf('#post') > 0){
    target = target.substring(0,target.indexOf('#post'));
  }
  
  //Ensure that a non-cached version of the parent page is loaded 
  if (target.indexOf('&nocache=true') == null || target.indexOf('&nocache=true') < 0){
    target = target + '&nocache=true';
  }
  //TODO Go directly to the post not just top of page
  if(window.opener != null){
    window.opener.location = target;
  }
}

/*
* Function to show the group of previous pages
*/
function previousFivePages(noOfGroups, currentPage, callFunction){
  var currentGroup = getCurrentPageGroup(noOfGroups, currentPage);
  
  for (var i=1; i<=noOfGroups; i++){
    var group = document.getElementById("pagegroup-"+i);
    
    //Show previous group 
    if (i==currentGroup-1){
      //Go to the last page in that group
      var goToPage = (currentGroup-1)*5;
      callFunction(goToPage);
      setElementClass(group, "pages-visible");
    
    //Hide rest of the groups
    } else {
      setElementClass(group, "pages-hidden");
    }
  }
}

/*
* Function to show the group of next pages
*/
function nextFivePages(noOfGroups, currentPage, callFunction){
  var currentGroup = getCurrentPageGroup(noOfGroups, currentPage);

  for (var i=1; i<=noOfGroups; i++){
    var group = document.getElementById("pagegroup-"+i);
    
    //Show next group
    if (i==currentGroup+1){
      //Go to the first page in that group
      var goToPage = (currentGroup*5)+1;
      callFunction(goToPage);
      setElementClass(group, "pages-visible");
      
    //Hide rest of the groups 
    } else {
      setElementClass(group, "pages-hidden");
    }
  }
}

/*
* Determine the current group this page is within
*/
function getCurrentPageGroup(noOfGroups, currentPage){
  var currentGroup = 0;
  //Determine the current group this page is within
  for (var i=1; i<=noOfGroups; i++){
    if ( (i*5)-4 <= currentPage && currentPage <= i*5 ) {
      currentGroup=i;
    }
  }
  return currentGroup;
}

/**
* Subscribe to an entity
*/
function followPost(postId){
  var htmlElement = document.getElementById("followpost");
  var data = "action=follow&post_id="+postId;
  
  //TODO need to show in progress
  sendDataReplaceHtml(URL_POSTS, data, htmlElement ,function() {
    //TODO need to hide in progress
    //TODO what if unsuccessful? e.g. post id invalid?
  });
}

/**
* Unsubscribe from an entity
*/
function unfollowPost(postId){
  var htmlElement = document.getElementById("followpost");
  var data = "action=unfollow&post_id="+postId;
  
  //TODO need to show in progress
  sendDataReplaceHtml(URL_POSTS, data, htmlElement ,function() {
    //TODO need to hude in progress
    //TODO what if unsuccessful? e.g. post id invalid?
  });
}

/**
* An admin can lock a translation so that no users can update that translation
*/
function lockTranslation(postId){
  var url = "service.php?type=translation";
  var data = "action=lock&post_id&post_id="+postId;
  sendData(url,data, function(){
    //Show Unlock link
    var lock = document.getElementById("lock");
    setElementClass(lock,'hidden');
    var unlock = document.getElementById("unlock");
    setElementClass(unlock,'');
  });
}

/**
* An admin can unlock a translation so that users can again update that translation 
*/
function unlockTranslation(postId){
  var url = "service.php?type=translation";
  var data = "action=unlock&post_id&post_id="+postId;
  sendData(url,data, function(){
    //Show Lock link
    var lock = document.getElementById("lock");
    setElementClass(lock,'');
    var unlock = document.getElementById("unlock");
    setElementClass(unlock,'hidden');
  });
}

/**
*   Show the title translation
*/
function showTranslationTitle(){
var nav = document.getElementById("nav");
  var title = document.getElementById("translation_title");
  var subtitle = document.getElementById("translation_subtitle");
  var text = document.getElementById("translation_text");
  
  setElementClass(title,'visible');
  setElementClass(subtitle,'hidden');
  setElementClass(text,'hidden');
  setElementClass(nav,'transtitle');
}

/**
*   Show the subtitle translation
*/
function showTranslationSubtitle(){
  var nav = document.getElementById("nav");
  var title = document.getElementById("translation_title");
  var subtitle = document.getElementById("translation_subtitle");
  var text = document.getElementById("translation_text");
  
  setElementClass(title,'hidden');
  setElementClass(subtitle,'visible');
  setElementClass(text,'hidden');
  setElementClass(nav,'transsubtitle');
}

/**
*   Show the subtitle translation
*/
function showTranslationText(){
var nav = document.getElementById("nav");
  var title = document.getElementById("translation_title");
  var subtitle = document.getElementById("translation_subtitle");
  var text = document.getElementById("translation_text");
  
  setElementClass(title,'hidden');
  setElementClass(subtitle,'hidden');
  setElementClass(text,'visible');
  setElementClass(nav,'transtext');
}

/*
* Called after a user has clicked on a Facebook Connect button
*/
function facebookConnectAccount(){
  var url = "service.php?type=fb";
  var data = "";
  sendData(url,data, function(){});
  
}

/*
 * Clear the post form after a user has submitted input
 */
function clearNewPostForm(){

  var textInputElement = document.getElementById("add_post_text");
  if (textInputElement!=null){
    textInputElement.value ="";
  }
  
  var locationInputElement = document.getElementById("add_post_location");
  if (locationInputElement!=null){
    locationInputElement.value = "";
  }

}

//TODO widgetapi.postListSendQueuedData
function showProgressIcon(){
  var progressBarDiv = document.getElementById("progress-bar"); 
  if (progressBarDiv==null){
    progressBarDiv = document.getElementById("narrow-progress-bar");  
  }
  
  if(progressBarDiv != null){
    progressBarDiv.style.visibility = "visible";
  }
}

/**
* Show in-progress indicator
*/
function showPostSubmitProgress(){
  var addPostDiv = document.getElementById("addpost_form_area");
  var progressBarDiv = document.getElementById("addpost_form_area_inprogress");
  
  if(addPostDiv != null){
    addPostDiv.style.display = "none";
  }
  
  if(progressBarDiv != null){
    progressBarDiv.style.display = "block";
  }
}

/**
* Hide in-progress indicator
*/
function hidePostSubmitProgress(){
  var addPostDiv = document.getElementById("addpost_form_area");
  var progressBarDiv = document.getElementById("addpost_form_area_inprogress");
  
  if(addPostDiv != null){
    addPostDiv.style.display = "block";
  }
  if(progressBarDiv != null){
    progressBarDiv.style.display = "none";
  }
  
  // clear the content out
  clearNewPostForm();
}

/**
* Submit an updated translation
*/
function fixTranslation(){
  var data = "type=translation&action=submitcorrection";
  var formnodes = document.retranslation_form;
  var postid;
  var referer;

  for(var i=0; i < formnodes.length; i++){
    var node = formnodes[i];
    
    if(node.name == 'url'){
      data += "&"+ node.name + "=" + escape(node.value);
    }
    else{
      data += "&"+ node.name + "=" + node.value;
    }
    if (node.name == 'postid'){
      postid = node.value;
    } 
    if (node.name == 'url'){
      url = node.value;
    }
    if (node.name == 'referer'){
      referer = node.value;
    }
  }
  
  var myAjax = new Ajax.Request("service.php", {method:'post', postBody:data, onSuccess: function(transport){
      var response = transport.responseText || "";

    //Refresh page
    if (referer!=""){
      //If translating message, set 'referer' so user can go back to inbox/sent items
      window.location='index.php?page=managetranslation&post_id='+postid+'&referer='+referer;
    } else {
      window.location='index.php?page=managetranslation&post_id='+postid;
    }
        
    var message = document.getElementById("translation-submitted-"+postid);
    message.style.display = "block";
    
    //Refresh parent
    refreshParent(encodeURI(url));
    
    },
    onFailure:translationFailed});
}


function fixTitleTranslation(){
  var data = "type=translation&action=submittitlecorrection";
  var formnodes = document.retranslation_title_form;
  var postid;
  var referer;

  for(var i=0; i < formnodes.length; i++){
    var node = formnodes[i];
    
    if(node.name == 'url'){
      data += "&"+ node.name + "=" + escape(node.value);
    }
    else{
      data += "&"+ node.name + "=" + node.value;
    }
    if (node.name == 'postid'){
      postid = node.value;
    } 
    if (node.name == 'url'){
      url = node.value;
    }
    if (node.name == 'referer'){
      referer = node.value;
    }
  }
  
  var myAjax = new Ajax.Request("service.php", {method:'post', postBody:data, onSuccess: function(transport){
      var response = transport.responseText || "";

    //Refresh page
    if (referer!=""){
      //If translating message, set 'referer' so user can go back to inbox/sent items
      window.location='index.php?page=managetranslation&post_id='+postid+'&referer='+referer;
    } else {
      window.location='index.php?page=managetranslation&post_id='+postid;
    }
        
    var message = document.getElementById("translation-submitted-"+postid);
    message.style.display = "block";
    
    //Refresh parent
    refreshParent(encodeURI(url));
    
    },
    onFailure:translationFailed});
}

function fixSubtitleTranslation(){
  var data = "type=translation&action=submitsubtitlecorrection";
  var formnodes = document.retranslation_subtitle_form;
  var postid;
  var referer;

  for(var i=0; i < formnodes.length; i++){
    var node = formnodes[i];
    
    if(node.name == 'url'){
      data += "&"+ node.name + "=" + escape(node.value);
    }
    else{
      data += "&"+ node.name + "=" + node.value;
    }
    if (node.name == 'postid'){
      postid = node.value;
    } 
    if (node.name == 'url'){
      url = node.value;
    }
    if (node.name == 'referer'){
      referer = node.value;
    }
  }
  
  var myAjax = new Ajax.Request("service.php", {method:'post', postBody:data, onSuccess: function(transport){
      var response = transport.responseText || "";

    //Refresh page
    if (referer!=""){
      //If translating message, set 'referer' so user can go back to inbox/sent items
      window.location='index.php?page=managetranslation&post_id='+postid+'&referer='+referer;
    } else {
      window.location='index.php?page=managetranslation&post_id='+postid;
    }
        
    var message = document.getElementById("translation-submitted-"+postid);
    message.style.display = "block";
    
    //Refresh parent
    refreshParent(encodeURI(url));
    
    },
    onFailure:translationFailed});
}

/**
* Error handling if submitting new translation fails
*/
function translationFailed(){
}

function finishedTranslation(postId){
  var data = "type=translation&action=finishedtranslation&post_id="+postId;
  
  var myAjax = new Ajax.Request("service.php", {method:'post', postBody:data, onSuccess: function(transport){
    window.location='index.php?page=managetranslation&post_id='+postId;
  },
    onFailure:translationFailed});
}


/*
* Load page x of links
*/
function loadLinksPage(page){
  window.location = "index.php?page=links&datapage="+page;
}

//TODO should be with param: jQuery.param({page:'managetranslation', action:'mytranslationhistory', datapage: page});
function updateMyTranslationHistoryPage(page){
  window.location = "index.php?page=managetranslation&action=mytranslationhistory&datapage="+page;
}

function updateUnassignedPage(page){
  window.location = "index.php?page=managetranslation&action=unassigned&datapage="+page;
}

function updateHighPriorityPage(page){
  window.location = "index.php?page=managetranslation&action=unassigned&status=high&datapage="+page;
}

function updateMyTranslationsPage(page){
  window.location = "index.php?page=managetranslation&action=mytranslations&datapage="+page;
}

jQuery(function(){

  if( typeof jQuery.fn.tabs == 'function' ) jQuery("#tabs").tabs();
  
  jQuery('.flag-link').live('click',function(){
    if( confirm('Are you sure you wish to flag this?') )
      {
        var that = this;
        jQuery.get(jQuery(this).attr('href'),function(resp){
          if( resp == 'success' )
          {
            jQuery(that).replaceWith("<span class='flagged'><img src='/static/images/icons/fam/flag_red.png' alt='flagged for admin review'/>Flagged for review.</span>");
          }
          else alert(resp);
          return false;
        });
      }
    return false;
  })
  
  jQuery('.delete-link').live('click',function(){
    if( confirm('Are you sure you wish to delete this?') )
    {
      var that = this;
      jQuery.get(jQuery(this).attr('href'),function(resp){
        if( resp == 'success' )
        {
          jQuery(that).parents('.result:first,.row:first').remove();
          
        }
        else alert(resp);
        return false;
      });
    }

    return false;
  });
  
  jQuery('.censor-link, .ignore-link').live('click',function(){
    var that = this;
    jQuery.get(this.href,function(){
      jQuery(that).parents('.row:first').remove();
    })
    return false;
  });



jQuery("a.subscribe").click(function(){
  jQuery('a.subscribe').replaceWith('<a href="#" class="unsubscribe">Subscribed</a>');
  jQuery('div#subscription_notice').show();
  jQuery('div#subscription_notice').replaceWith('<div id="subscription_notice"> Subscribed! Watch for updates in your <a href="/index.php?page=messaging">subscriptions</a></div>');
     setTimeout( function() {  $( '#subscription_notice' ).fadeOut(); }, 5000 );  
});

jQuery("a.unsubscribe").click(function(){
  jQuery('a.unsubscribe').replaceWith('<a href="#" class="subscribe">Unsubscribed</a>');
  jQuery('div#subscription_notice').show();
  jQuery('div#subscription_notice').replaceWith("<div id='subscription_notice'>You have been unsubscribed from this event.</div>").toggle();
     setTimeout( function() {  $( '#subscription_notice' ).fadeOut(); }, 5000 );  
});

  // hollaback to debugger
  jQuery("#debugger").append("<code>jquery.js, meedan.js</code>");
})

var loadingHtml = '<div id="loading_indicator">جاري التنفيذ <img src="static/images/indicator_circle_ball.gif" alt="جاري التنفيذ" /></div>';

