// JavaScript Document 

var errFunc = function(t) { 
  alert('Error ' + t.status + ' -- ' + t.statusText); 
} 

function initSortCats (elementNameToMakeSortable)
{
  Sortable.create(elementNameToMakeSortable,{
                                            onChange: showSaveCatDisplayOrderButton,
                                            handle: 'moveCat',
                                            dropOnEmpty:false,
                                            constraint: 'vertical'
                                            });
} //end function initSortCats

function saveCatDisplayOrder(relRoot,elementName,functionToCall,dbTableNameToUpdate,catIDNameToSort)
{
  new Ajax.Request(relRoot+'ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&dbTableName='+dbTableNameToUpdate+'&displayOrderArrayName='+elementName+'&catIDNameToSort='+catIDNameToSort, { 
  method: 'POST',onSuccess: cbSavedCatDisplayOrder, onFailure:errFunc,parameters: Sortable.serialize(elementName)
  }); 
  Element.hide('sortCats');
  $('div_responseSortCat').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
  //destroy sortable object
  //Sortable.destroy(elementName);
}

function cbSavedCatDisplayOrder (saved)
{ 
  if(saved.responseText == 'saved')
  {
    Element.hide('div_responseSortCat');
    $('div_saveCatDisplayOrder').style.display = 'none';
    Element.show('sortCats');
  }
  else //not saved
  {
    $('div_responseSortCat').innerHTML = "<div align='center' style='margin-top: 50px;color: red;'>Det gick inte att spara ändringarna.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\"div_responseSortCat\");$(\"div_saveCatDisplayOrder\").style.display = \"none\";Element.show(\"sortCats\")' class='submitButton'></div>";
  }
}

function showSaveCatDisplayOrderButton()
{
  //if the display order has been changed, show the save button
  $('div_saveCatDisplayOrder').style.display = '';
}

function saveDisplayOrder(sortObjElementName,dbTableName,dbTableIDName,divProcessName,divSavingName)
{
   new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=saveDisplayOrder&dbTableName='+dbTableName+'&dbTableIDName='+dbTableIDName+'&displayOrderArrayName='+sortObjElementName, {
            method: 'POST',
            encoding: 'iso-8859-1',
            onSuccess: function(saved){
              if(saved.responseText == 'saved')
              {
                //Element.hide('div_savingProductDisplayOrder_process');
                $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna har blivit sparade.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");Element.hide(\""+divSavingName+"\");' class='submitButton'></div>";
              }
              else if (saved.responseText == 'noChange')
              {
                $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna var samma som tidigare.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");Element.hide(\""+divSavingName+"\")' class='submitButton'></div>";
              }
              else //not saved
              {
                $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;color: red;'>Det gick inte att spara ändringarna.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");Element.hide(\""+divSavingName+"\");' class='submitButton'></div>";
              }
              
            }, 
            onFailure:errFunc,
            onLoading: function(){$(divProcessName).show()},
    				onLoaded: function(){setTimeout(function(){$(divProcessName).hide();$(divSavingName).hide()},2000)},
            parameters: Sortable.serialize(sortObjElementName)
  }); 
}

//Ex. if the name of the input element is: input_categoryName_93 the baseFieldName is: categoryName
function editSaveField(baseFieldName,id,action,dbTableName,dbFieldToUpdate,divProcessName,fieldControllerID)
{
  if(fieldControllerID == '')
    fieldControllerID = id;
  var editName = 'editSaveFieldControler_'+fieldControllerID+'_edit';
  var saveName = 'editSaveFieldControler_'+fieldControllerID+'_save';
  var cancelName = 'editSaveFieldControler_'+fieldControllerID+'_cancel';
  var fieldTextName = 'span_a_' + baseFieldName +'_'+id;
  var fieldInputName = 'span_input_' + baseFieldName +'_'+id;
  if(action == 'edit')
  {
    Element.hide(fieldTextName);
    Element.show(fieldInputName);
    //hide edit image and show save and cancel
    Element.hide(editName);
    Element.show(saveName);
    Element.show(cancelName);
  }
  else if (action == 'cancel')
  {
    Element.hide(fieldInputName);
    Element.show(fieldTextName);
    //reset the value for the input edit field
    $('input_' + baseFieldName +'_'+id).value = $('span_' + baseFieldName +'_'+id).innerHTML;
    //hide cancel and save image and show edit
    Element.show(editName);
    Element.hide(saveName);
    Element.hide(cancelName);
  }
  else if (action == 'save')
  {
    var content = $('input_' + baseFieldName +'_'+id).value;
    if(content == '') //field cannot be empty
    {
      Element.show(divProcessName);
      $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;color: red;'>ERROR: fältet kan inte vara tomt. Var snäll och ange ett värde.<BR><br><input type='button' name='ok' value='OK' onClick='$(\""+divProcessName+"\").style.display = \"none\";' class='submitButton'></div>";
      return false;
    }
    //make ajax call
    new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=saveSingleElement', { 
      method: 'POST',
      postBody: 'dbTableName='+dbTableName+'&dbTableIDValue='+id+'&dbFieldToUpdate='+dbFieldToUpdate+'&contentValue='+content,
      onSuccess: function(saved) {
                    if(saved.responseText == 'saved')
                    {
                      $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna har blivit sparade.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");Element.hide("+saveName+");Element.hide("+cancelName+");Element.show("+editName+");' class='submitButton'></div>";
                      //update the field to display the new value
                      $('span_' + baseFieldName +'_'+id).innerHTML = $('input_' + baseFieldName +'_'+id).value;
                    }
                    else if (saved.responseText == 'noChange')
                    {
                      $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna var samma som tidigare.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");Element.hide("+divSavingName+")' class='submitButton'></div>";
                      //reset the field to display the old value since there was no change
                      $('input_' + baseFieldName +'_'+id).value = $('span_' + baseFieldName +'_'+id).innerHTML;
                    }
                    else //not saved
                    {
                      $(divProcessName).innerHTML = "<div align='center' style='margin-top: 20px;color: red;'>Det gick inte att spara ändringarna.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\""+divProcessName+"\");' class='submitButton'></div>";
                    }
                    //change the view -> show the original view
                    Element.hide(fieldInputName);
                    Element.show(fieldTextName);
                    Element.show(editName);
                    Element.hide(saveName);
                    Element.hide(cancelName);
    
                    /*
                    var processDiv = document.createElement('div');
                    processDiv.setAttribute("id",'process_' + baseFieldName +'_'+id);
                    processDiv.setAttribute("style","display:none;position:absolute;margin-top:0px;width:100%;");
                    processDiv.setAttribute("class","admin_processingDiv");
                    
                    if(saved.responseText == 'saved')
                    {
                      processDiv.innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna har blivit sparade.<BR><br><input type='button' name='ok' value='OK' onClick='$(input_" + baseFieldName +"_"+id+").removeChild($(input_" + baseFieldName +"_"+id+"));Element.hide("+saveName+");Element.hide("+cancelName+");' class='submitButton'></div>";
                      $('input_' + baseFieldName +'_'+id).appendChild(processDiv);
                    }
                    else if (saved.responseText == 'noChange')
                    {
                      processDiv.innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna var samma som tidigare.<BR><br><input type='button' name='ok' value='OK' onClick='$(input_" + baseFieldName +"_"+id+").removeChild($(input_" + baseFieldName +"_"+id+"));Element.hide("+saveName+");Element.hide("+cancelName+");' class='submitButton'></div>";
                      $('input_' + baseFieldName +'_'+id).appendChild(processDiv);
                    }
                    else //not saved
                    {
                      processDiv.innerHTML = "<div align='center' style='margin-top: 20px;color: red;'>Det gick inte att spara ändringarna.<BR><br><input type='button' name='ok' value='OK' onClick='$(input_" + baseFieldName +"_"+id+").removeChild($(input_" + baseFieldName +"_"+id+"));Element.hide("+saveName+");Element.hide("+cancelName+");' class='submitButton'></div>";
                      $('input_' + baseFieldName +'_'+id).appendChild(processDiv);
                    }
                    setTimeout(function(){
                                $("input_" + baseFieldName +"_"+id).removeChild($("input_" + baseFieldName +"_"+id));
                                Element.hide(saveName);
                                Element.hide(cancelName);
                                Element.show(editName);
                                },2000);
                    */
                  }
      , onFailure:errFunc,
      onLoading: function(){
                            //hide cancel and save image and show edit
                            Element.hide(saveName);
                            Element.hide(cancelName);
                            Element.show(divProcessName);
                          },
			onLoaded: function(){setTimeout(function(){
                                        //$(divProcessName).hide();
                                        Effect.Fade(divProcessName, { duration: 1.0 });
                                      },2000)},
      encoding: 'iso-8859-1'
      }); 
      
    
  } //end if action
  
} //end function editSaveField



function saveAdminPageSettings(formName,relRoot,functionToCall)
{
  new Ajax.Request(relRoot+'ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall, { 
  method: 'POST',onSuccess:updateAdminPageSettings, onFailure:errFunc,parameters: $(formName).serialize(true) 
  }); 
  //Element.hide('div_adminPageSettingsContent');
  $('div_adminPageSettingsContent').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
  return false; 
} //end function savePageSettings()

var updateAdminPageSettings = function(t) {
  $('div_adminPageSettingsContainer').innerHTML = t.responseText; 
}

function setID ()
{
  //CHECK TO SEE IF INSERTASNEW HAS BEEN CHECKED, IF SO, CHANGE ID TO NEW
  if($('insertAsNew') != null)
  {
    if($('insertAsNew').checked == true)
    {
      $('idShow').innerHTML = 'new';
      $('id').value = 'new';
    }
    else
    {
      $('idShow').innerHTML = $('oldID').value;
      $('id').value = $('oldID').value;
    }
  }
}

function saveAdminForm(formName,relRoot,functionToCall,divToUpdateOnSuccess,divToUpdateOnError,showSavingNoticeInDivID)
{
  if($('pageID2') != null)
    var extraGet = '&pageID2='+$('pageID2').value;
  else
    var extraGet = '';
  
  if(tinyMCE != null)
    tinyMCE.triggerSave();
  
  new Ajax.Updater({ success: divToUpdateOnSuccess, failure: divToUpdateOnError },relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+extraGet, { 
  method: 'POST',parameters: $(formName).serialize(true)
  });
  //Element.hide('div_adminPageSettingsContent');
  $(showSavingNoticeInDivID).innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
  
  /**/
  return false; 
} //end function saveAdminForm()

function removeNL(s){ 
  return s.replace("/[\n\r\t]/g,"); 
}


function saveSingleEditorElement(dbTableName,id,tinyMCE_editorIdName,dbFieldToUpdate)
{
  if(typeof(eval(tinyMCE.get(tinyMCE_editorIdName))) == "undefined")
    return;
  tinyMCE.triggerSave();
  //grab the instance of the editor to be saved
  var ed = tinyMCE.get(tinyMCE_editorIdName);
  //grab the content of the editor to be saved
  //var content = ed.getContent();
  var content = $(tinyMCE_editorIdName).serialize(); 
  //make sure to extract the fieldName= from the content string to later be added to contentValue=
  content = content.replace(tinyMCE_editorIdName+"=","");
  //make ajax call
    new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=saveSingleElement', { 
      method: 'POST',
      postBody: 'dbTableName='+dbTableName+'&dbTableIDValue='+id+'&dbFieldToUpdate='+dbFieldToUpdate+'&contentValue='+content,
      onSuccess: function(saved) {
                    Element.show('div_save_process');
                    if(saved.responseText == 'saved')
                    {
                      $('div_save_process').innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna har blivit sparade.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\"div_save_process\");' class='submitButton'></div>";
                    }
                    else if (saved.responseText == 'noChange')
                    {
                      $('div_save_process').innerHTML = "<div align='center' style='margin-top: 20px;'>Ändringarna var samma som tidigare.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\"div_save_process\");' class='submitButton'></div>";
                    }
                    else //not saved
                    {
                      $('div_save_process').innerHTML = "<div align='center' style='margin-top: 20px;color: red;'>Det gick inte att spara ändringarna.<BR><br><input type='button' name='ok' value='OK' onClick='Element.hide(\"div_save_process\");' class='submitButton'></div>";
                    }
                    setTimeout(function(){
                                Effect.Fade('div_save_process', { duration: 1.0 });
                              },3000);
                    //close editor so we display just the text again.
                    toggleEditor(tinyMCE_editorIdName);
                  }, 
      onFailure:errFunc,
      onLoading: function(){
                  ed.setProgressState(1); // Show progress
                },
			onLoaded: function(){
                  ed.setProgressState(0);// Hide progress 
                },
      encoding: 'iso-8859-1'
      }); 

} //end function saveSingleElement

function getProductSearchResult(formName,page,pageNrRequested,searchType)
{
  //update the page requested
  $('pageNrRequested').value = pageNrRequested;
  new Ajax.Request(relRoot+'/ajax?page='+page+'&functionToCall=getProductSearchResult&searchType='+searchType, { 
      method: 'POST',
      parameters: $(formName).serialize(true),
      onSuccess: function(result) {
                    $('div_containerSearchResult').innerHTML = result.responseText;
                    //Effect.Fade('div_containerSearchProcess', { duration: 1.0 });
                    Element.hide('div_containerSearchProcess'); // Hide result
                    Effect.Appear('div_containerSearchResult', { duration: 1.0 });
                  }, 
      onFailure:errFunc,
      onLoading: function(){
                  Element.hide('div_containerSearchResult'); // Hide result
                  //$('div_containerSearchProcess').show; // Show progress
                  Effect.Appear('div_containerSearchProcess', { duration: 1.0 });
                },
      encoding: 'iso-8859-1'
      }); 
  return false;
}

function getSpecificProductSearchLists(formName,page,pageNrRequested,searchType)
{
  new Ajax.Request(relRoot+'/ajax?page='+page+'&functionToCall=getSpecificProductSearchLists&searchType='+searchType, { 
      method: 'POST',
      parameters: $(formName).serialize(true),
      onSuccess: function(result) {
                    $('div_searchProductSelectLists').innerHTML = result.responseText;
                    //Effect.Fade('div_containerSearchProcess', { duration: 1.0 });
                    //Element.hide('div_containerSearchProcess'); // Hide result
                    Effect.Appear('div_searchProductSelectLists', { duration: 1.0 });
                    //======== get the search result for this selection =============//
                    //clear search string
                    $('searchString').value = '';
                    //set the searchLike value to be exact
                    //$('searchLike_exact').checked = true;
                    getProductSearchResult(formName,page,pageNrRequested,'specificProductSearchResult');
                  }, 
      onFailure:errFunc,
      onLoading: function(){
                  //Element.hide('div_searchProductSelectLists'); // Hide result
                  //$('div_containerSearchProcess').show; // Show progress
                  Effect.Appear('div_containerSearchProcess', { duration: 1.0 });
                },
      encoding: 'iso-8859-1'
      }); 
  return false;
}

/*
function saveSingleElement(dbTableName,id,nicEditorIdName,dbFieldToUpdate)
{
  
  if(typeof(eval(nicEditors.findEditor(nicEditorIdName))) == "undefined")
    return;
  
  //get nic editor value before saving content.
  var content = nicEditors.findEditor(nicEditorIdName).getContent();
  alert(content);
  new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=saveSingleElement', { 
  method: 'POST',postBody: 'dbTableName='+dbTableName+'&dbTableIDValue='+id+'&dbFieldToUpdate='+dbFieldToUpdate+'&contentValue='+content,onSuccess: function(transport) {
                    alert(transport.responseText);
                    Element.hide(nicEditorIdName+'_process');
                  }
, onFailure:errFunc,encoding: 'iso-8859-1'
  }); 
  //$(nicEditorIdName+'_process').innerHTML = "<div align='center' style='margin-top: 30px;' class='admin_processingDivText'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
  Element.show(nicEditorIdName+'_process');
} //end function saveSingleElement


function cb_saveSingleElement(t)
{
  //get nic editor value before saving content.
  alert(t.responseJSON);
  alert(t.responseText);
  //nicEditors.findEditor(nicEditorIdName).setHTML() = t.responseText;
  Element.hide(nicEditorIdName+'_process');
  $(nicEditorIdName+'_process').innerHTML = "<div align='center' style='margin-top: 30px;' class='admin_processingDivText'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
} //end function cb_saveSingleElement

*/




function saveAdminFormUsingIframe(formName,uploadTargetName,action,relRoot,functionToCall,divToUpdateOnSuccess,divToUpdateOnError,showSavingNoticeInDivID)
{
  var makeIframePost = false;
  
  if($('newDocumentFileName') != null && $('newDocumentFileName').value != '')
    makeIframePost = true;
    
  if(makeIframePost == true)
  {
    //only do a iframe post if a new file has been requested to upload.
    $(formName).target = uploadTargetName;
    $(formName).action = relRoot+'/ajax?page='+page+'&adminCall=TRUE&noAjaxCall=TRUE&functionToCall='+functionToCall;
    Element.hide('div_adminForm');
    $('div_adminFormProcess').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/savingAnimation.gif' border='0'><BR>Sparar</div>";
    Element.show('div_adminFormProcess');
    return true;
  }
  else
  {
    saveAdminForm(formName,relRoot,functionToCall,divToUpdateOnSuccess,divToUpdateOnError,showSavingNoticeInDivID);
    return false;
  } //end if makeIframePost
} //end function saveAdminDocumentForm()

var updateAdminFormFromIframe = function(result,id,action,page) 
{
  new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=saveDocument&fromIframeSaving=TRUE&id='+id+'&action='+action, { 
  method: 'GET',onSuccess:updateAdminFormAfterIframeCall, onFailure:errFunc
  });
} //end function updateAdminFormFromIframe

var updateAdminFormAfterIframeCall = function(t) {
  $('div_adminContainer').innerHTML = t.responseText; 
  var divHeight = (($('div_adminForm').offsetHeight + 260) + 'px');
  $('div_adminContainer').style.height = divHeight;
  
  Element.hide('div_adminFormProcess');
  Element.show('div_adminForm');
} //end function updateAdminForm


function getAdminForm(functionToCall,id,action)
{
  //make sure that other admin forms are closed
  closeAdminForm('div_adminPageSettingsContainer');
  new Ajax.Updater('div_adminContainer',relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&id='+id+'&action='+action, { 
  method: 'GET' 
  }); 
  $('div_adminContainer').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/loadingAnimation.gif' border='0'><BR>Laddar</div>";
  new Effect.BlindDown('div_adminContainer', { duration: 0.5 });
  return false; 
} //end function getAdminForm()

function showAdminBannerForm(functionToCall,action,id)
{
  new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&action='+action+'&id='+id, { 
  method: 'GET',onSuccess: function (t) {
  alert(t.responseText);
                              $('div_adminForm').innerHTML = t.responseText; 
                              var divHeight = (($('div_adminForm').offsetHeight + 260) + 'px');
                              $('div_adminForm').style.height = divHeight;
                           }, onFailure:errFunc
  }); 
  /*new Ajax.Updater('div_adminForm',relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&action='+action+'&id='+id, { 
  method: 'GET'
  });
  */ 
  $('div_adminForm').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/loadingAnimation.gif' border='0'><BR>Laddar</div>";
  new Effect.BlindDown('div_adminForm', { duration: 0.5 });
  return false; 
} //end function showAdminForm()

function showAdminForm(functionToCall,formName,pageID2)
{
  if(pageID2 != '')
    var extraPageID2 = '&pageID2='+pageID2;
  else
    var extraPageID2 = '';
  new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+extraPageID2, { 
  method: 'POST',onSuccess:updateAdminForm, onFailure:errFunc,parameters: $(formName).serialize(true) 
  }); 
  
  /*new Ajax.Updater('div_adminForm',relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall, { 
  method: 'POST',parameters: $(formName).serialize(true) 
  });
  */ 
  $('div_adminForm').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/loadingAnimation.gif' border='0'><BR>Laddar</div>";
  new Effect.BlindDown('div_adminForm', { duration: 0.5 });
  return false; 
} //end function showAdminForm()

var updateAdminForm = function(t) {
  alert(t.responseText);
  $('div_adminForm').innerHTML = t.responseText; 
  var divHeight = (($('div_adminForm').offsetHeight + 260) + 'px');
  $('div_adminForm').style.height = divHeight;
  //Event.observe(window, 'load', createEditorInstance());

} //end function updateAdminForm

function backToEditForm(backFromBaseName,selectedID)
{
  $('div_adminContainer').innerHTML = $('div_adminContainerTmp').innerHTML;
  $('div_adminContainerTmp').innerHTML = '';
  $(backFromBaseName+'ID').focus();
  if(selectedID == '')
    selectedID = $F(backFromBaseName+'ID');
  new Ajax.Updater('div_htmlOptions_'+backFromBaseName, relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=getAdminSimpleSelects&dbTableName='+backFromBaseName+'&selectedID='+selectedID, { 
  method: 'GET',
  onSuccess: function (t) {
              //alert(t.responseText);
              },
  onFailure: errFunc,
  onLoading: function(){
              
            },
	onLoaded: function(){
              
            }
  }); 
  
} //end function backToEditForm

function getCategoryList(functionToCall)
{
  /*new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&pageID='+$F('pageID2'), { 
  method: 'GET',onSuccess:updateAdminForm, onFailure:errFunc 
  }); */
   new Ajax.Updater('div_adminContainer',relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall='+functionToCall+'&pageID2='+$F('pageID2'), { 
  method: 'GET'
  }); 
  $('div_adminContainer').innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/loadingAnimation.gif' border='0'><BR>Laddar</div>";
  new Effect.BlindDown('div_adminContainer', { duration: 0.5 });
  return false; 
} //end function getCategoryList

function showAdminPageSettings()
{
  closeAdminForm('div_adminContainer');
  new Effect.BlindDown('div_adminPageSettingsContainer', { duration: 0.5 });
  if($('div_response') != null)
  {
    if($('div_response').style.display == '')
      $('div_response').style.display == 'none';
  }
  return false;
}
  
function closeAdminForm(divNameToClose)
{
  if(divNameToClose == '')
  {
    if($('div_adminPageSettingsContainer') != null)
    {
      if($('div_adminPageSettingsContainer').style.display == '')
        new Effect.BlindUp('div_adminPageSettingsContainer', { duration: 0.5 });
    }
    
    if($('div_adminContainer') != null)
    {
      if($('div_adminContainer').style.display == '')
        new Effect.BlindUp('div_adminContainer', { duration: 0.5 });
    }
  }
  else
  {
    if($(divNameToClose) != null)
    {
      if($(divNameToClose).style.display == '')
        new Effect.BlindUp(divNameToClose, { duration: 0.5 });
    }
  }
  return;
} //end function closeAllAdminForms

function hideElement(divIdName)
{
  if($(divIdName) != null)
    Element.hide(divIdName);
  return;
}

function uploadDoc(formName,uploadTargetName,id,action)
{
  if (action == 'deleteRecord')
    var newAction = 'deleteDocument';
  else
    var newAction  = 'saveDocument';
    
  
  //document.getElementById(formName).target = 'upload_target';
  $(formName).target = uploadTargetName;
  $(formName).action = relRoot+'/ajax?page='+page+'&adminCall=TRUE&noAjaxCall=TRUE&functionToCall=uploadDocument&id='+id+'&action='+action;
  
  return true;
}

var updateAdminForm = function(t) {
  $('div_adminForm').innerHTML = t.responseText; 
  var divHeight = (($('div_adminForm').offsetHeight + 260) + 'px');
  $('div_adminForm').style.height = divHeight;
  //Event.observe(window, 'load', createEditorInstance());

} //end function updateAdminForm

function openImageUploadImage(rootURL,id,productName)
{
  var uploadImageWindow = window.open(rootURL+'upload/?adminCall=TRUE&noAjaxCall=TRUE&functionToCall=getUploadProductImagePage&id='+id+'&productName='+productName,'uploadImageWindow1','width=650,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=yes');
} //end function openImageUploadImage

function openImageUploadImageForContact(rootURL,id,firstName,lastName)
{
  var uploadImageWindow = window.open(rootURL+'upload/?adminCall=TRUE&noAjaxCall=TRUE&functionToCall=getUploadContactImagePage&id='+id+'&firstName='+firstName+'&lastName='+lastName,'uploadImageWindow1','width=650,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=yes');
} //end function openImageUploadImage

/* 
imageTableType is the dbTableName that has been set in the image table, Ex.  'content' or 'product'
*/
function getProductImages(imageTableType,id,divName)
{
  /*new Ajax.Request(relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=getProductImages&productID='+productID, { 
  method: 'GET',onSuccess:cb_getProductImages, onFailure:errFunc
  });*/ 
  new Ajax.Updater(divName,relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=getAdminImages&imageTableType='+imageTableType+'&id='+id, { 
  method: 'GET'
  }); 
  $(divName).innerHTML = "<div align='center' style='margin-top: 50px;'><img src='"+relRoot+"/graphics/loadingAnimation.gif' border='0'><BR>Laddar</div>";
  new Effect.BlindDown(divName, { duration: 0.5 });
  return false; 
} //end function getProductImages()







function uploadDocument(uploadDivID,functionToCall,id,action)
{
  new AjaxUpload('div_test', {action: relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=uploadDocument&id='+id+'&action='+action});

  /*
  new AjaxUpload(uploadDivID, {
                           action: relRoot+'/ajax?page='+page+'&adminCall=TRUE&functionToCall=uploadDocument&id='+id+'&action='+action,
                           onSubmit : function(file , ext)
                                      {
                                    		if (! (ext && /^(jpg|png|jpeg|gif|pdf|doc|docx|txt)$/.test(ext)))
                                        {
                                    			// extension is not allowed
                                    			alert('Error: invalid file extension');
                                    			// cancel upload
                                    			return false;
                                    		}
                                    	}
                                  });
  */
  return false; 
} //end function getAdminForm()

function startUpload()
{
  document.getElementById('div_adminFormProcess').style.visibility = 'visible';
  document.getElementById('div_adminForm').style.visibility = 'hidden';
  return true;
}

function stopUpload(success)
{
  var result = '';
  if (success == 1)
  {
     result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
  }
  else 
  {
     result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
  }
  document.getElementById('div_adminFormProcess').style.visibility = 'hidden';
  document.getElementById('div_adminForm').innerHTML = result + '<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
  document.getElementById('f1_upload_form').style.visibility = 'visible';      
  return true;   
}

function printContent(divIDtoGetContentFrom)
{
  //remove any links if printed on the page
  if ($('div_detailPageLinks') != null)
  {
    var detailPageLinks = $('div_detailPageLinks').innerHTML;
    $('div_detailPageLinks').innerHTML = '';
  }
  var printText = $(divIDtoGetContentFrom).innerHTML;
  //if links existed, make sure that the links will be written back to the main window
  if ($('div_detailPageLinks') != null)
    $('div_detailPageLinks').innerHTML = detailPageLinks;
    
  var docprint = window.open("","docprint","toolbar=no,location=no,directories=no,menubar=yes,scrollbars=yes,width=650, height=600, left=100, top=25"); 
   docprint.document.open(); 
   
   docprint.document.write('<html><head><title>Skriv ut</title>');
   docprint.document.write('<link href="'+cssPath+'style.for.printing.php" rel="stylesheet" type="text/css" />'); 
   //docprint.document.write('<script type="text/javascript" src="'+jsPath+'prototype.js"></script>'); 
   //docprint.document.write('<script type="text/javascript" src="'+jsPath+'functions.js"></script>');  
   docprint.document.write('</head><body onLoad="self.print();">');    
   docprint.document.write(printText);       
   docprint.document.write('<BR><br>');    
   docprint.document.write('</body></html>'); 
   docprint.document.close(); 
   docprint.focus(); 
} //end function printContent





function unserialize(data){
    // Takes a string representation of variable and recreates it  
    // 
    // version: 903.3016
    // discuss at: http://phpjs.org/functions/unserialize
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays 
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
    
    var error = function (type, msg, filename, line){throw new window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;
        
        buf = [];
        for(var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;

        if(!offset) offset = 0;
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
        
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
        
        switch(dtype){
            case "i":
                typeconvert = new Function('x', 'return parseInt(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "b":
                typeconvert = new Function('x', 'return (parseInt(x) == 1)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "d":
                typeconvert = new Function('x', 'return parseFloat(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "n":
                readdata = null;
            break;
            case "s":
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;
                
                readData = read_chrs(data, dataoffset+1, parseInt(stringlength));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if(chrs != parseInt(stringlength) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case "a":
                readdata = {};
                
                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;
                
                for(var i = 0;i < parseInt(keys);i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
                    
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
                    
                    readdata[key] = value;
                }
                
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    return _unserialize(data, 0)[2];
} //end function unserialize

