function setCookie(c_name,value,expiredays)
{
   var exdate=new Date();
   exdate.setDate(exdate.getDate()+expiredays);
   document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(cookiename) {
 var cookiestring=""+document.cookie;
 var index1=cookiestring.indexOf(cookiename);
 if (index1==-1 || cookiename=="") return ""; 
 var index2=cookiestring.indexOf(';',index1);
 if (index2==-1) index2=cookiestring.length; 
 return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

/****************************/
/* End of Cookies Utils    */
/**************************/

function serialize(s)
{
   serial = $.SortSerialize(s);
   return serial
};

function serializeMe()
{
  s= serialize(['c0', 'c1']);
  a1 = s.o['c0'].concat(s.o['c1']);
  return a1;
};   

function getOptions(a)
{
   answer = Array();
   for (i=0; i<a.length; i++){
      answer[i] = Object();
      answer[i] = {
         id: $('#'+a[i]).attr('id'),
         cl: $('#'+a[i]).parent().attr('id'),
         titl: $('#'+a[i]).children('.wrap').children('.handler').children('.title').text(),
         contentUrl: $('#'+a[i]).attr('contentUrl'),
         state: $('#'+a[i]).attr('state')
      };

   }
   return answer;
}

//var options = 


function putContent(obj, action, title){
 $(obj).html('<div class="wait"></div>');
 action += '&rand='+new Date().getTime()+'&keywords='+keyword;
 $("#status").html('Now loading: '+title);
 $.get(action, function(data){
   $(obj).html(data);
   if (data.match(/tabsHere/i)) tabsInit(obj);
   $("#status").html(title + " has been loaded.");
 });
}

function reloadBox(obj){
 $(obj).html('<div class="wait"></div>');
 action += '&rand='+new Date().getTime()+'&keywords='+keyword;
 $.get(action, function(data){
   $(obj).html(data);
   if ($('.tabsHere').length>0) tabsInit();
 });

}


function tabsInit(obj){

   sfm = $('.sfmAjax', obj);
   tab = $('.tab1', obj)
   $('form', sfm).submit( function() {
      additional = $('input[@name=additional]').attr('value');
      $(tab).html('<div class="wait "></div>')
      $.get($( $(tab).prev().children('.sel') ).attr('url')+'&keywords='+keyword+'&additional='+additional, '',function(data){$(tab).html(data)});

      return false;
   });

   $('.tabLabels a', this).each(function(){
      $(this).bind('click',function(){
         if (this.className != 'sel') {
            tab = $(this).parent().parent().children('.tab1')

            additional = $('input[@name=additional]').attr('value');
            putContent(tab ,$(this).attr('url')+'&keywords='+keyword+'&additional='+additional, $(this).text())

            $(this).parent().children('a').removeClass('');
            $(this).addClass('sel');
            
         }
         return false;
      })
   });
   this.className = 'tabs';
}

/****************************/
/* Sortables init          */
/**************************/


function bindHideShow(){
   $('.hide').bind("click", function(){
      box = $(this.parentNode.parentNode.parentNode);
      if (box.attr('state')!= 'closed'){
//         box.children(".text").slideUp(100);
         box.children(".text").hide();
         box.children(".text").html(box.children(".text").html());
         this.firstChild.src="images/landing/box/expand.png"
         box.attr('state',"closed");
      }else{
//         box.children(".text").slideDown(100);
         box.children(".text").show();
         this.firstChild.src="images/landing/box/collapse.png"
         box.attr('state',"open");
      }
         doSettings();
         return false;
    });
}


function initSortables(){
   $("#c0").html("");
   $("#c1").html("");
if(keyword){
   $("#slogan").remove();
   for(i=0, l=portalOptions.length; i<l; i++){
      a=portalOptions[i];
      doBox(a.id, i, a.titl, a.contentUrl, a.state, $('#'+a.cl+''))
   }
      $('.column').Sortable(
         {
            accept :       'box',
            helperclass:   'sortHelper',
            activeclass :  'sortableactive',
            hoverclass :   'sortablehover',
            opacity:       0.8,
            handle:        '.handler',
            fx:            100,
            revert:        true,
            floats:        true,
            tolerance:     'pointer',
/*            onChange : function(ser)
            {
            },
            onStart : function()
            {
//               $.iAutoscroller.start(this, document.getElementsByTagName('body'));
            },*/
            onStop : function()
            {
  //             $.iAutoscroller.stop();
                  doSettings('save');
            }
         }
      )
    $('[@state=closed] .text').hide()
    $('[@state=closed] .hide img').attr('src',"images/landing/box/expand.png")
}
}

/****************************/
/* End of Sortables init   */
/**************************/

/* Save settings */
function doSettings(){
  portalOptions = getOptions(serializeMe());
  setCookie('options',$.toJSON(portalOptions),'2');
}

/****************************/
/* Box processor           */
/**************************/
//<a href=\"#\"><img src=\"images/landing/buttons/edit.gif\" /></a> <a href=\"#\"><img src=\"images/landing/buttons/close.gif\" /></a>
function doBox(id, num, titl, contentUrl, state,el){
   $(el).append("<div id=\""+id+"\" num=\""+num+"\" class=\"box\"><div class=\"wrap\">\n<div class=\"handler\"><div class=\"buttons\"><a href=\"#\" class=\"hide\"><img src=\"images/landing/box/collapse.png\" /></a></div><div class=\"title\"><img src=\"images/landing/engines/big/"+id+".gif\" />"+titl+"</div></div><div class=\"text\"></div><div class=\"bl\"></div></div></div>");
   $('#'+id).attr('state', state)
   $('#'+id).attr('contentUrl', contentUrl)
   putContent($('#'+id).children('.wrap').children('.text'), contentUrl, titl);
}
/****************************/
/* End of Box processor    */
/**************************/

function AllKwFormInit(){
 $('#allForm [@type=image]').click(function(){
   keyword=$("#allKw").attr('value');
   $.get('spell.php?ajaxCall=true&keyword='+keyword, function(data){
     initSortables();
     if(data != keyword){
	     result = 'Did you mean:<a href="javascript:spellchecked(\''+data+'\');"><b><i>'+data+'</i></b></a>';
	     $("#spell").html(result);
     }
     else{
	     $("#spell").html('');
     }
   });
 });
 $('#allKw').keypress(function(e){
   if (e.keyCode == 13){
   keyword=($("#allKw").attr('value'))?($("#allKw").attr('value')):"";
   $.get('spell.php?ajaxCall=true&keyword='+keyword, function(data){
     initSortables();
     if(data != keyword){
	     result = 'Did you mean:<a href="javascript:spellchecked(\''+data+'\');"><b><i>'+data+'</i></b></a>';
	     $("#spell").html(result);
     }
     else{
	     $("#spell").html('');
     }
   });
   }
 });
}

function themesInit(){
   opt = $('#options');
   optBody = $(opt).children('.body')

   if (getCookie('theme')>2) {
       theme=getCookie('theme');
   }else{
       theme = 'blue'
   }
   $('#'+theme+'Theme').addClass('sel');
   $('#options .selector td').click(function(){
      alert(this.id)
   })

   $(opt).children('.onOff').click(function(){
      if ($(optBody).css('display')!='none') {$(optBody).hide() }else{$(optBody).show()}
   })
}
function spellchecked(data){
	$("#allKw").attr('value',data);
	$('#allForm [@type=image]').click();
}


/****************************/
/* Main Program            */
/**************************/


$(document).ready(
   function () {

if (getCookie('options').length<2)
   {
      $.get("landingSettings.php?rand="+new Date().getTime(), function(data){
   
      portalOptions=$.parseJSON(data);
      initSortables();
      bindHideShow();
      AllKwFormInit();
      themesInit();

      })
   }
   else
   {
      portalOptions=$.parseJSON(getCookie('options'));
      initSortables();
      bindHideShow();
      AllKwFormInit();
      themesInit();

   }
   

   }
);
