var rogtopia = {
  'version' : '1.0.0',
  'sections' : {
    'jquery-js' : '<span>UI</span>, <span>Ajax</span>, <span>Animation</span>, <span>Dom Manipulation</span>, <span>Speedy Event Binding</span> Enhancements with <span>jQuery</span> and <span>Javascript</span>',
    'html-css' : '<span>Web Layout</span> mastered through <span>HTML</span> and <span>CSS</span> following modern <span>web standards</span> and language <span>compliancy.</span>',
    'general' : '<span>Roger</span> likes other things too; Such as <span>Guitar</span>, <span>Eating</span> and <span>Drinking</span>. Does that make him less <span>Geek</span>?',
    'photoshop' : '<span>Web Design</span> with Adobe <span>Photoshop</span> - Create beautiful <span>raster graphics</span> for your <span>web project</span>.'
  },
  'checkAgent' : function () {
    if($.browser.msie && $.browser.version<8) {
      var cook = getCookie('askIE');
      if (cook) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  },
  'promptIE' : function () {
    $('#dialog').dialog({
      'bgiframe':true,
      'modal':true,
      'resizable':false,
      'draggable':false,
      'autoOpen':false,
      'width':640,
      'height':460,
      'title':'Browser Notice : You are Missing Out!',
      'buttons' : {
        'cancel' : function () { $(this).dialog('destroy'); },
        'continue' : function () {
          jAlert('I will remind you in <strong>7 days</strong> about your non-standards compliant browser.<br>Sorry to hear the bad news :(', 'Alert Dialog');
          setCookie('askIE','true',14);
          $(this).dialog('destroy');
        }
      }
    });
    var _d = new Date();
    var nocache = _d.getTime();
    $('#dialog').empty().load('http://rogtopia.com/files/documents/ie-notice.html?nocache='+nocache,function() { $(this).dialog('open'); });
  },
  'showSite' : function (_url) {
     $('#dialog').dialog({
      'bgiframe':true,
      'modal':true,
      'resizable':false,
      'draggable':false,
      'autoOpen':false,
      'width':980,
      'height':620,
      'title':'Forwarded to ' + _url,
      'buttons' : {
        'close' : function () { $(this).dialog('destroy'); },
        'forward' : function () { history.go(1); },
        'back' : function () { history.go(-1); }
      }
    });
    $('#dialog').empty().html('<iframe src="' + _url + '" marginwidth="0" marginheight="0" style="width:100%;height:100%;" scrolling="auto" frameborders="no"></frame>').dialog('open');
  },
  'youTube' : function (_vid,_title) {
    var _ytURI = 'http://www.youtube.com/watch?v=' + _vid;
    $('#dialog').dialog({
      'bgiframe':true,
      'modal':true,
      'resizable':false,
      'draggable':false,
      'autoOpen':false,
      'width':640,
      'height':580,
      'title':'YT: ' + _ytURI,
      'buttons' : {
        'close' : function () { $(this).dialog('destroy'); },
        'visit directly' : function () { window.open(_ytURI); $(this).dialog('destroy'); }
      }
    });
    $('#dialog').empty().html('<h3>'+_title+'</h3><object width="600" height="400"><param name="movie" value="http://www.youtube.com/v/'+_vid+'&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+_vid+'&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="600" height="400"></embed></object>').dialog('open');
  },
  GO : function (_url) {
    window.location.href = _url;
  }
};

//jquery mini plugs
$.fn.truncate = function(_length,_delim) {
  if(!_delim) { _delim = ''; }
  return this.each(function () {
    var txt = $(this).text();
    if(txt.length>_length) {
      txt = txt.substr(0,_length-_delim.length);
      $(this).text(txt+_delim);
    }
  });
}
$.fn.youtubes = function() {
  return this.each(function () {
    var _vid = $(this).attr('href').split('=')[1];
    var _title = $(this).attr('title');
    $(this).bind('click', function(event) {
      event.preventDefault();
      rogtopia.youTube(_vid,_title);
    });
  });
}
$.fn.poplink = function() {
  return this.each(function () {
    var _url = $(this).attr('href');
    $(this).bind('click', function(event) {
      event.preventDefault();
      rogtopia.showSite(_url);
    });
  });
}
$.fn.bookmark = function() {
  return this.each(function () {
    var _url = window.location.href;
    var _title = $('title').text();
    _title = URLEncode(_title);
    $(this).attr('href',$(this).attr('href') + _url + '&title=' + _title);
  });
}
$(document).ready(function(){
  if(!rogtopia.checkAgent()) {
    rogtopia.promptIE();
  }
  $('.cat-recent li a').truncate(40,'..');
  $('.sidebar li a').truncate(44,'..');
  $('.youtube-link').youtubes();
  $('.pop-link').poplink();
  $('.social-bookmark').bookmark();
  
  // fix archive link text
  $('.cat-recent .archived a').text('older articles');
  
  // code syntax highlight
  $('.content pre').chili();
  
  // setup tooltips
  $('*[title]').qtip( { tip : { color : '#0d4249' }, position : { corner : { target: 'topRight', tooltip: 'bottomLeft' }, adjust : { x : -20 } }, style : { border : { width: 2, radius: 2, color: '#2a8b97' }, width: { min : 20, max : 400 }, padding: 10, textAlign: 'left', tip: true, name: 'light' } });
  
  // cross-domain to *.rogtopia.com if from live - utilizes ajax.rogtopia.com system.
  if( !window.location.href.match('viviti.com') && !window.location.href.match('127.0.0.1') ) {
    document.domain = 'rogtopia.com';
  }
  if(window.location.href.match('/entries/')) {
    var loc = window.location.href.replace('http:\/\/').split('/');
    $('.page-fold .ui-wrapper').empty().html('<h2 style="margin-top:17px;">'+rogtopia.sections[loc[2]]+'</h2>');
  }
  if(window.location.href.match('/entries\\?query')) {
   var keyword = window.location.href.split('=')[1].split('&')[0].replace(/\+/g,' ');
   $('.page-fold .ui-wrapper').empty().html('<h2 style="margin-top:17px;">Looks like <span>you</span> are trying to <span>find</span> something. Let us see what we can <span>dig up</span> about <span><strong>' + keyword + '</strong></span></h2>');
  }
});


// general common utils
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(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
function URLEncode(plaintext)
{
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" +                    // Numeric
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +    // Alphabetic
                    "abcdefghijklmnopqrstuvwxyz" +
                    "-_.!~*'()";                    // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++ ) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+";                // x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
                          "(URL encoding only supports 8-bit characters.)\n" +
                          "A space (+) will be substituted." );
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
};

function URLDecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
       if (ch == "+") {
           plaintext += " ";
           i++;
       } else if (ch == "%") {
            if (i < (encoded.length-2)
                    && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
                    && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
                plaintext += unescape( encoded.substr(i,3) );
                i += 3;
            } else {
                alert( 'Bad escape combination near ...' + encoded.substr(i) );
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
           plaintext += ch;
           i++;
        }
    } // while
   return plaintext;
};
