var currSize = 1;

function swichStyleSheetSrc(size) {
    var styleName = 'size'+size;
    $('link[rel*=STYLE][title]').each(function() {
        this.disabled = true;
        if($(this).attr('title')==styleName) {
            this.disabled = false;
        }
    });
    $.cookie('styles',size,{expires:7,path:'/'});
}

function setBookmark() {
    var bookmarkurl = location.href;
    var text = document.title;
    text = text.replace(/:/ ,"");
    text = text.replace(/\*/ ,"");
    text = text.replace(/\?/ ,"");
    text = text.replace(/\\/ ,"");
    text = text.replace(/"/ ,"");
    text = text.replace(/</ ,"");
    text = text.replace(/>/ ,"");
    text = text.replace(/|/ ,"");
    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(text, bookmarkurl,"");
    } else if( window.external ) { // IE Favorite
        window.external.AddFavorite( bookmarkurl, text);
    } else if(window.opera && window.print) { // Opera Hotlist
        return true;
    }
}

function getPageToolUrl(param) {
     // grep current location
      newLoc = self.location.href.toString();
      var baseURL;
      // check if there are any additional information in the location string
      // and extract the baseURL from location string
     if(newLoc.match(/(.+)[\?#]/)) {
        baseURL = newLoc.match(/(.+)[\?#]/)[1];
      } else {
        baseURL = newLoc;
      }
      // add existing parameter information
      if (self.location.search && self.location.search != "") {
        baseURL+=self.location.search+'&'+param+'=1';
      } else {
        baseURL+='?'+param+'=1';
      }
      // add exisiting hash information
      if(self.location.hash && self.location.hash!="") {
        baseURL+=self.location.hash;
      }
      return baseURL;
}

$().ready(function() {
    // ie only functions
    if($.browser.msie) {
         // avoid background flickering
         try {document.execCommand("BackgroundImageCache",false,true);} catch(e){}
         $('link[title*=bw]').each(function() {
            this.disabled = true;
        });
    }
    // page tools
    // bookmarking
    $('#bookmark').click(function(){setBookmark(); return false;});
    // black and white version
    $('#bwversion').click(function(){
      $('link[title*=bw]').each(function() {this.disabled = false;});
      $(this).hide();
      $('#colversion').show();
    });
    $('#colversion').click(function(){
      $('link[title*=bw]').each(function() {this.disabled = true;});
      $(this).hide();
      $('#bwversion').show();
    });
    // text version
    $('#textversion').click(function(){
      var url = getPageToolUrl('tty');
      location.href = url;
      return false;});
    // print version
    $('#print').each(function(){
      var url = getPageToolUrl('print');
      // relpace the original page Tool content with the new url
      $(this).replaceWith('<a href="'+url+'" target="_blank" id="print"><span>'+
      $(this).text()+'</span></a>');
    });
    // end of page tools

    // fontsize (cookie reading to grep current size)
    if($.cookie('styles')) {
        currSize = parseInt($.cookie('styles'));
        var isActive = false;
        $('link[rel*=STYLE][title]').each(function() {
              if($(this).attr('rel').indexOf('ALTERNATE')==-1
                && $(this).attr('title')=='size'+currSize) {
                    isActive = true;
              }
        });
        $('#fs_size'+currSize).addClass('active');
        if(!isActive) {
            swichStyleSheetSrc(currSize);
        }
    }
    // fontsizer...
    var maxSizes = $('#FontSizer .size').size();
    if(maxSizes > 0) {
        if(currSize==1) {
            $('#fs_minus').addClass('disabled');
        } else if(currSize==maxSizes) {
            $('#fs_plus').addClass('disabled');
        }
        $('#FontSizer .size').click(function() {
            currSize = parseInt(this.id.replace(/fs_size/g,''));
            $('#FontSizer .size').each(function(){$(this).removeClass('active');});
            $(this).addClass('active');
            if(currSize==1) { $('#fs_minus').addClass('disabled');}
            else {$('#fs_minus').removeClass('disabled');}
            if(currSize==maxSizes) { $('#fs_plus').addClass('disabled');}
            else {$('#fs_plus').removeClass('disabled');}
            swichStyleSheetSrc(currSize);
            return false;
        });
         $('#fs_minus').click(function(){
            if(currSize > 1) {
                currSize--;
                $('#FontSizer .size').each(function(){$(this).removeClass('active');});
                $('#fs_size'+currSize).addClass('active');
                if(currSize==1) { $('#fs_minus').addClass('disabled');}
                else {$('#fs_minus').removeClass('disabled');}
                $('#fs_plus').removeClass('disabled');
                swichStyleSheetSrc(currSize);
            }
            return false;
         });
         $('#fs_plus').click(function(){
                 if(currSize < maxSizes) {
                     currSize++;
                     $('#FontSizer .size').each(function(){$(this).removeClass('active');});
                     $('#fs_size'+currSize).addClass('active');
                     if(currSize==maxSizes) { $('#fs_plus').addClass('disabled');}
                     else {$('#fs_plus').removeClass('disabled');}
                     $('#fs_minus').removeClass('disabled');
                     swichStyleSheetSrc(currSize);
                 }
                 return false;
         });
     }

        if(typeof(jQuery.jScrollPane)=='object') {
      $('#pane1').jScrollPane({showArrows:true,scrollbarWidth:15});
      if($('#pane2').size()>0) {
        $('#pane2').jScrollPane({showArrows:true,scrollbarWidth:15});
      }
      $('#tab2').hide();
      $('div.tabset a:eq(0)').addClass('active');
      $('div.tabset a').click(function() {
         var t = $(this).attr('href');
         $('div.tabset a').each(function() {
            var tt =  $(this).attr('href');
            if(tt!=t) {
              $(this).removeClass('active');
              $(tt).hide();
            }
         });
         if(!$(this).is('.active')) {
           $(this).addClass('active');
           $(t).show();
         }
         return false;
      });
    }
    $('.home #StageShadow').after('<div id="CSF">&nbsp;</div>');

    $('#CountrySites, #CSF, #CountrySitesMainNav').css({'cursor':'pointer'}).click(function(){
        if($('#countrypop').size()==0) {
          var h = $('#CountrySites button span').text();
          var _pw = $('<div id="countrypop"></div>').appendTo('body');
          _pw.append('<h3>'+h+'</h3>');
          var _pc = $('<div class="close"><span>X</span></div>').appendTo(_pw);
          $(_pc).click(function() {$('#countrypop').hide();});
          var cols = [];
          for(c=0; c<3; c++) {
            var cp = $('<div id="col'+c+'" class="col"></div>').appendTo(_pw);
            cols[c] = $('<div></div>').appendTo(cp);
          }
          $select = $('#CountrySites select');
          var data = {};
          var total = 0;
          $('option',$select).each(function() {
            var text = $(this).text();
            var val = $(this).val();
            if($(this).parents('optgroup').size()>0) {
              var p = $(this).parents('optgroup')[0];
              var id = $(p).attr('label');
              if(!data[id]) {
                data[id] = [];
                total++;
              }
              data[id][data[id].length] = {'value':val,'text':text};

            }
          });
		  var perColumnBase		= Math.floor(total/3);
		  var perColumnMod		= total % 3;
		  var perColumns		= [perColumnBase, perColumnBase, perColumnBase];
		  for (var x = 0; x < perColumnMod;x++) {
				perColumns[x] += 1;
		  }
          
          var cCol = 0;
          var cnt=0;
          var colBreak = perColumns[0];
          for(a in data) {
            if(cnt==colBreak) {
              cCol+=1;
			  colBreak += perColumns[cCol];
            }
            cols[cCol].append('<h4>'+a+'</h4>');
            for(x=0; x<data[a].length; x++) {
                cols[cCol].append('<p><a href="'+data[a][x]['value']+'" target="_blank">'+data[a][x]['text']+'</a></p>');

            }
            cnt++;
          }
           $('.col a',_pw).click(function() {$('#countrypop').hide();});
        }
        var de = document.documentElement;
        var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
        var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
        var $pw = $('#countrypop');
        try {
          var l = parseInt((w - 800)/2);
              var t= parseInt((h - 500)/2);
              $pw.css({'left':l,'top':t}).show();
              } catch(e) {
          $pw.show();
        }
    });



     $('#PostsFormContainer').not('.error-occured').hide();
     $('#PostsFormToggle').click(
      function() {
        if($('#PostsFormContainer').is(':visible')) {
          $('#PostsFormContainer').hide();
        } else {
          $('#PostsFormContainer').show();
        }
      }
     );



     $('li.post img, li.post strong').click(function() {
        var cp = $(this).parents('li');
        var cid = $(cp).attr('rel');
        var data = {};
        if($('#pdetail').size()==0) {
          $('#Wrapper').append('<div id="pdetail"><div id="PostClose"><span>X</span></div><div id="PostBox"><div id="PostImg"><img src="" /></div><div id="PostCon"><div id="PostTeaser"></div><div id="PostText"></div><div id="PostUser"></div><div><span  id="PostDate"></span> - <span id="PostCountry"></span>, <span id="PostCity"></span></div></div></div></div>');
          $('#PostClose').click(function(){$('#pdetail').hide();});
        }
        $(cp).append('<div class="loading"><img src="/html/images/main/css/loading_green.gif"/><span>Loading, please wait...</span></div>');
        data['postid'] = cid;
        $.get('/scripts/include/wrapper/posts_detail.php',data,function(json){
            try {
                eval('resp = ' + json);
                if(resp.data) {
                    $('#pdetail img').attr({'src':resp.data.img});
                    $('#PostTeaser').html(resp.data.teaser);
                    $('#PostText').html(resp.data.text);
                    $('#PostDate').html(resp.data.date);
                    $('#PostCity').html(resp.data.city);
                    $('#PostUser').html('By '+resp.data.name);
                    $('#PostCountry').html(resp.data.country);
                    $('#PostUser').html(resp.data.user);
                    $('#pdetail').show();
                    $('div.loading').remove();
                }
            } catch(ex) {
                $('#pdetail').hide();
                $('div.loading').remove();
            }
        });
     });

});