/*
   KULMIO SISÄLLÖNHALLINTA
   hiski valli 2010
*/
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
/* ACTIVATE SYSTEM */
/* --------------- */



jQuery.fn.kaasuvuoto = function(linkName,kpath)
{
   
   // if path not provided this is the default, otherwise use provided path
   if (kpath == undefined) kaasuPath = '/system';
   else kaasuPath = kpath+'system';
   
   // if no login link text provided this is the default
   if (linkName == undefined || linkName=='undefined') linkName = 'Hallinta';
   
   // build login link
   var lgnLink = '<a href="javascript:void(0)" onclick="loginModal()" class="kaasulgn" title="Siirry sivuston hallintaan"><span>'+linkName+'</span></a>';
   
   // add login link
   jQuery(this).append(lgnLink);
   
   /* check session if already logged in, if so, execute scripts and go live */
   /* ajax now */
   $.ajax({
      type: "POST",
      url: kaasuPath+"/controlpanel/session.php",
      success: function(data)
      {
         data = jQuery.trim(data);
         // if login session is over 90, then admin is good
         var loginval = data.split("_", 2)
         if((loginval[0]=='loggedin')&&(parseInt(loginval[1])>=90))
         {       
            jQuery(".fti").css({display:'none'});
            // load scripts
         
            executeCssAndScripts(kaasuPath+"/controlpanel", "start");
            // fire panel
            executeCssAndScripts(kaasuPath+"/controlpanel", "end");
            
            getPanel(kaasuPath,"loggedin", kaasuPanel);
            
         }
         else
         {
            
            jQuery(".fti").css({display:'inline'});
         }
      }
   });

   // site user login popup button
   
   if ($("#userloginpopuplink").length != 0)
   {
      jQuery("#userloginpopuplink").bind("click", function(){
      
            var content = '<div class="logoutbox">';
            content += '<div class="hd text" style="padding-top: 5px;"></div>';
            content += '<div class="bd text" style="padding-top: 15px;"><h1 class="sitelogin">Jäsenalue</h1></div>';
            content += '<div class="ft text" style="padding: 0 20px;"><p><b>Tervetuloa sivuston jäsenaleelle.</b></p><p>Syötä käyttäjätunnuksesi ja salasanasi <br /> ja kirjaudu sisään.</p>'+jQuery(this).parent().next('div').html()+'</div>';
            content += '</div>';

            $.colorbox({
               html:content,
               current: "",
               previous: "",
               next: "",
               close: "Sulje",
               initialWidth: 0,
               initialHeight: 0,
               width: 340,
               opacity: 0.72
           })
            
      });	      
   }


};

function getPanel(kaasuPath,alreadylogged,f)
{
   $.ajax({
      type: "GET",
      url: kaasuPath+"/controlpanel/controlpanel.php?val="+Math.random(),
      success: function(data){
         if (alreadylogged==null)
         {
            kaasuRebuildMenu(getUrlVars()["page"]);
         }
          
         jQuery(data).prependTo($("body"));
         jQuery("body").animate({ paddingTop: '150px' }, "normal");

         jQuery("#kaasupanel").animate({top:'1px'}, "normal",function(){
            if (typeof f == "function") f(alreadylogged,kaasuPath);
         });
         
      }
   });
}



/* EXECUTE SCRIPTS */
/* --------------- */

function scripter(url,type)
// test cross browser stuff !
{
   var script = document.createElement( 'script' );
   script.type = 'text/javascript';
   if (type)
   {      
   } else {
      script.src = url;
      script.setAttribute("async","async");
      $(script).appendTo("head");
   }
   
}

function csser(url,media)
// test cross browser stuff !
{
   var css = document.createElement( 'link' );
   css.type = "text/css";
   css.rel = "stylesheet"
   css.media = media || "all";
   css.href = url;
   //$(css).appendTo("head");
   document.getElementsByTagName('head')[0].appendChild(css);
   
}


function executeCssAndScripts(scriptPath, event)
{
   if (event=='start')
   {
      var jsfiles = "";
      /* Add system css to header */
      csser(scriptPath+"/css/controlpanel.css","all");         
      /* Add system javascripts (manually for now) to end of page */
      //scripter(scriptPath+"/js/jquery.nyroModal-1.6.2.pack.js");
      //moved to site scripts folder
      
   }
   else if (event=='end')
   {
      /* kaasuvuoto controlpanel javascript */
      scripter(scriptPath+"/js/controlpanel.js");  
      /* swf & ajax upload tools */
      scripter(scriptPath+"/js/ajaxupload.js");  
      scripter(scriptPath+"/js/uploadify/jquery.uploadify.v2.1.0.min.js"); 
      scripter(scriptPath+"/js/uploadify/swfobject.js");
   } else if (event=='after')
   {
      
      /* forms validation */
      scripter(scriptPath+"/js/validateforms.js");  
      /* jquery ui for draggable elements */
      scripter(scriptPath+"/js/jquery-ui-1.7.2.custom.min.js");
      /* ckeditor + jquery plugin */
      scripter(scriptPath+"/ckeditor/ckeditor.js");
      scripter(scriptPath+"/ckeditor/adapters/jquery.js");
   }
};


/* LOGIN FUNCTIONS */
/* --------------- */

/* launch login modal box */
function loginModal(){
      /* execute scripts for kaasuvuoto */
      executeCssAndScripts(kaasuPath+"/controlpanel","start");

      var content = '<div class="kaasupopdata"><div class="hd text" style="padding-top: 5px; height: 126px;"><img src="system/controlpanel/img/sitrus.png" alt="Sitrus logo" style="padding: 15px 15px 0px 15px;"/></div>';
      content += '<div class="bd text"><span class="warning"></span></div>';
      content += '<div class="ft text"><form action="javascript:void(0)" method="post" onsubmit="initLogin(doLogin);" id="loginform"><fieldset style="padding-bottom: 15px;"><label for="username">Tunnus&nbsp;:&nbsp;&nbsp;</label><input type="text" name="username" id="username" maxlength="100" value=""/><label for="password">Salasana&nbsp;:&nbsp;&nbsp;</label><input type="password" name="password" id="password" maxlength="100" value=""/></fieldset><button class="center" type="submit" id="kaasusbt">&nbsp;&nbsp;KIRJAUDU&nbsp;&nbsp;</button>&nbsp;&nbsp;<button class="center" type="button" onclick="$.colorbox.close()">&nbsp;&nbsp;SULJE&nbsp;&nbsp;</button></form></div></div>';
      
      if($.browser.msie && parseFloat($.browser.version) < 7){
        //not supperted in bakcend (ie6)
      content = '<div class="kaasupopdata"><div class="hd text" style="padding-top: 35px;">Selaintasi (IE6) ei tueta hallinnassa<br/><br/><button class="center" type="button" onclick="$.colorbox.close()">&nbsp;&nbsp;SULJE&nbsp;&nbsp;</button></div></div>';
      } 

      modalBox(content, 340, 340, null, 'close');
// modal

}

/* rebuild menu */

function kaasuRebuildMenu(page){

   if (!page)
   {
      page="undefined";
   }

   $.ajax({
         type: "GET",
         url: kaasuPath+"/inc/build.inc.php",
         data: 	"rebuildmenu=true&page="+page,
         success: function(data){
            jQuery("#mainmenu").html(data);
         }
   });   
}

/* execute login animation */
function initLogin()
{
   
   $('html').animate({scrollTop:0},'normal');
   $('body').animate({scrollTop:0},'normal',doLogin);   
}

/* execute login */
function doLogin()
{
   endLogin();
}
function endLogin()
{
   
   jQuery("#kaasusbt").attr({ disabled: "disabled" });
   var user = jQuery("#username").val();
   var pass = jQuery("#password").val();   
   jQuery.ajax({
      url: kaasuPath+'/controlpanel/loginnow.php?jslogin=true&password='+pass+'&username='+user,
      success: function(data){
        data = jQuery.trim(data);
        split = data.split("_");

         if (split[0]=='brutefail')
         {
            jQuery(".warning").html("Käyttäjätunnus lukittu "+split[1]+" sekunniksi. Sisäänkirjautumista yritetty liian monta kertaa epäonnistuneesti viimeisen 20min aikana tällä käyttäjätunnuksella.");
         } else {
            jQuery(".warning").html("Tunnus/Salasana ei kelpaa. Yritä uudelleen.");
         }
         
         // admin privileges
         if((split[0]=='loggedin')&&(split[1]>=90)){
               kaasuRebuildMenu(getUrlVars()["page"]);
               content = '<div class="kaasupopdata"><div class="hd text" style="padding:25px 25px 0px 25px;"><h1>Kirjaudutaan...</h1></div><div class="ft text" ><div class="waitResults"></div></div></div>';
               modalBox(content, false, false, 'startpanel',null);
               jQuery("#kaasusbt").removeAttr("disabled");    
               jQuery(".fti").css({display:'none'});
         } else {         
               jQuery(".warning").css({ display: "none" });
               jQuery("#kaasusbt").removeAttr("disabled");
               jQuery(".fti").css({display:'inline'});
               jQuery(".warning").slideDown("slow",function(){
                  
                  $.fn.colorbox.resize();
                  });
               
         } 
      }
   });
   return false;
}


/* launch logout check modal box */
function kaasuLogoutCheck(){
   var lgoutData = '<div class="kaasupopdata"><div class="hd text" style="padding-top:25px;"><h1>Kirjaudu ulos</h1></div><div class="bd text" style="padding: 15px 15px 30px 15px">Kirjaudu ulos verkkosivujen hallinnasta<br/>ja jatka selailua normaalisti?</div><div class="ft text" ><button class="left" type="submit" onclick="kaasulogout();">&nbsp;&nbsp;Kyllä&nbsp;&nbsp;</button>&nbsp;<button class="right" type="submit" onclick="$.colorbox.close();">&nbsp;&nbsp;Ei&nbsp;&nbsp;</button></div></div>';

   modalBox(lgoutData, false, false,null,'close');
}

/* execute logout */
function kaasulogout(){
   $.colorbox.close();
   jQuery(".fti").css({display:'inline'});
   /* animate and remove tabs and panel */
   
   if($(".kaasutabs").length)
   {
      // if tabs
      jQuery(".kaasutabs").slideUp("normal",function(){
         jQuery("body").animate({
            paddingTop: '0px'
         }, "slow");
         
         jQuery("#kaasupanel").animate({top:'-150'}, "slow",function(){
            jQuery(this).remove();
            jQuery(".kaasutabs").remove();
         });            
      });      
   } else {
      jQuery("body").animate({
         paddingTop: '0px'
      }, "slow");
      
      jQuery("#kaasupanel").animate({top:'-150'}, "slow",function(){
         jQuery(this).remove();
         jQuery(".kaasutabs").remove();
      });            
   }
   


   
   jQuery.get(""+kaasuPath+"/controlpanel/sess-destroy.php?killsession=true",function(){
      kaasuRebuildMenu(getUrlVars()["page"]);
   });
   
   
   
   kaasuPanelUnbinder();
   kaasuEditOff('.contentarea');
   
}

function modalBox(content, widthz, heightz, ajax, close){
      
    $.colorbox({
         overlayClose: false,
         escKey: false,
         arrowKey: false,
         onLoad: function() {
            if(close == 'close')
            {
              $('#cboxClose').remove();
            }
         },
        width: widthz,
        height: heightz,
        escKey: false,
        arrowKey: false,
        html:content,
        current: "{current} / {total}",
        previous: "Viim.",
        next: "Seur.",
        close: "Sulje",
        initialWidth: 0,
        initialHeight: 0,
        opacity: 0.72,
        slideshow: false,
        onComplete: function() {
            $.fn.colorbox.resize();
            if (ajax=="startpanel")
            {
               executeCssAndScripts(kaasuPath+"/controlpanel", "end");   
               getPanel(kaasuPath,null, kaasuPanel);	         
            }
            // if ajax submit modal
            else if (ajax!=null)
            {
               var options = { 
                       success:
                       function(resp)
                       {	
                               if (resp)
                               {
                                       var variable = $(ajax).attr('id');
                                       var id = variable.substring(0, 1);
                                       var folder = variable.substring(4, variable.lenght);
                                       
                                       if (ajax=='.addGalForm')
                                       { 
                                         changeGallery(id,folder);	
                                       } else if (ajax=='.addFileForm'){
                                         changeFilelist(id,folder);	
                                       }
                                                                       
       
                                       var errorcontent = '<div class="kaasudata"><div class="hd"><h1>Toiminto suoritettu</h1></div>';
                                       errorcontent += '<div class="ft"><span class="text">'+resp+'<p>Voit sulkea tämän ikkunan. Lataa sivusto uudelleen selaimessasi nähdäksesi muutokset varsinaisen sivuston puolella.</p><button type="submit" class="center" onclick="$.colorbox.close();">&nbsp;&nbsp;Sulje ikkuna&nbsp;&nbsp;</button></span></div></div>';
                                       modalBox(errorcontent,false, false, null, 'close');
                                       
                               } else { /* nothing? */ }
                       }
               }; 
               $(ajax).ajaxSubmit(options);
               $('button:last', elts.content).focus();
               	      
            } else {

            }
            
        }
    });
      

}

/* ajax submit */
$.fn.ajaxSubmit = function(e) { /* Change a form's submission type to ajax */ this.submit(function(){ var params = {}; $(this) .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea") .filter(":enabled") .each(function() { params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; }); $("body").addClass("curWait"); $.post(this.getAttribute("action") + "?call=ajax", params, function(xml){ $("body").removeClass("curWait"); strError = "Unable to submit form. Please try again later."; oFocus = null; $("AjaxResponse", xml).each(function() { strRedirect = this.getAttribute("redirecturl"); strError = this.getAttribute("error"); oFocus = this.getAttribute("focus"); }); if (strError.length == 0) { window.location = strRedirect; } else { alert("The following errors were encountered:\n" + strError); $("div.formErrors").html("<h3>Error<\/h3><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal"); if (oFocus) $("#" + oFocus).get(0).focus(); } }); return false; }); return this; } 
