// JavaScript Document
//alert(String(window.location).replace(/#.*/, ''));

function safe_refresh(){
	
	window.location = String(window.location).replace(/#.*/, '');
}

function std_ajax_return(json){
	if (json.msg !=null){
		alert(json.msg);
	}else if (json.error !=null){
		if ($('#recaptcha_response_field').size()>0){
			Recaptcha.reload();
		}
		alert(json.error);
	}else if (json.url !=null){
		$('input[type=submit]').attr('disabled','disabled');
		window.location = json.url;
	}else if (json.refresh !=null){
		$('input[type=submit]').attr('disabled','disabled');
		window.location = window.location;
	}
}

var cart_hints_showed = false;
function show_cart_hints(){
	if (!cart_hints_showed){
		cart_hints_showed = true;
		window.scroll(0,0);
		$('#cart_hints').fadeIn('slow');
		$('#a_cart').addClass('green_cart');
		$('#span_a_cart').show();		
	}
}
function datepicker_setup(date_dummy, date_real, on_select_func_name, default_date){
	var settings = { 
		dateFormat: $.datepicker.RFC_822,
		showOn: "both",
		buttonImage: "/public/calendar.gif",
		buttonImageOnly: true,
		duration: 0,
		changeFirstDay: false,
		closeAtTop: false,
		altField: 'input[name="'+date_real+'"]', 
		altFormat: "yy-mm-dd"
	};
	if (typeof(on_select_func_name) == 'function'){
		settings.onSelect = on_select_func_name;
	}

	if (typeof(default_date) == 'object'){
		settings.defaultDate = default_date;
	}
	
	$('input[name="'+date_dummy+'"]').datepicker(settings);
}

function setup_date_update(prefix){
	prefix=prefix+'_';
	var update_date=function(){	
		$('input[name='+prefix+'date]').val($('select[name='+prefix+'year]').val()+'-'+$('select[name='+prefix+'month]').val()+'-'+$('select[name='+prefix+'day]').val());
		$('input[name='+prefix+'date]').blur();		
	};
	$('input[name='+prefix+'date]').siblings('select').change(update_date);	
}

function init_year_month_day(prefix){
	prefix=prefix+'_';

	var digits=$('input[name='+prefix+'date]').val().split('-');
	for (var i=0;i<3;i++){
		if (digits[i][0]=='0') digits[i]=digits[i].substr(1,1);
	}
	$('select[name='+prefix+'year]').val(digits[0]);
	$('select[name='+prefix+'month]').val(digits[1]);	
	$('select[name='+prefix+'day]').val(digits[2]);	
}

function init_hour_min_ampm(prefix){
		
	prefix=prefix+'_';
	var digits=$('input[name='+prefix+'time]').val().split(':');


		if (digits[0][0]=='0') digits[0]=digits[0].substr(1,1);
	
	var ampm='am';
		
	if (digits[0]>=12){
		ampm='pm';
		digits[0]-=12;
	}
	if (digits[0]==0) digits[0]=12;
	
	$('select[name='+prefix+'hour]').val(digits[0]);
	$('select[name='+prefix+'min]').val(digits[1]);	
	$('select[name='+prefix+'ampm]').val(ampm);		
}

function setup_time_update(prefix){
	prefix=prefix+'_';

	var update_time=function(){	
		var hour =parseInt($('select[name='+prefix+'hour]').val());
		var minute =$('select[name='+prefix+'min]').val();
		var ampm=$('select[name='+prefix+'ampm]').val();
		if (ampm=='pm'){
			hour+=12;
		}
		if (hour==12 || hour==24)	hour-=12;		
		$('input[name='+prefix+'time]').val(hour+':'+minute+':00');
		$('input[name='+prefix+'time]').blur();		
	};
	$('input[name='+prefix+'time]').siblings('select').change(update_time);	
}

function get_ajax_handler(success_function){
	var ajax_handler={
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				dataType: "json",
				success: success_function
			});
			
		}
	};
	return ajax_handler;
}

var small_width = 160;
var small_height = 160;
var big_width = 380;
var big_height = 380;
function js_toggle(){
	if ($('#play_movie').height() != big_height && $('embed[name=play_movie]').height() != big_height){
		js_bigger();
	}else{
		js_smaller();
	}
}
function js_bigger(){
	$('#play_movie').height(big_height).width(big_width);
	$('embed[name=play_movie]').height(big_height).width(big_width);	
}
function js_smaller(){
	$('#play_movie').height(small_height).width(small_width);
	$('embed[name=play_movie]').height(small_height).width(small_width);	
}

////////////////////////////////
//utility functions
/////////////////////////////

function get_shorter_text(str, maxrows, maxcharsperrow){

    var ret = "";
    var k=0;
	var linepos = 0;
    while (str != undefined && str[k]!=undefined){
        if (str[k]=="\n" || linepos == maxcharsperrow){
			linepos =0;
			maxrows -= 1;
		}else{
			linepos++;
		}
        if (maxrows <=0){
            break;
        }
        ret += str[k];
		k++;
    }
    return ret;
}

function init_short_text(div_expr, new_class_name, maxrows, maxcharsperrow){
	$(div_expr).each(function(){
		var less_div = $('<div></div>');
		if (new_class_name !='') less_div.addClass(new_class_name);
		
		var decoded = html_entity_decode($(this).html());
		var newDecoded = get_shorter_text(decoded, maxrows, maxcharsperrow);
		$(this).html(nl2br($(this).html()));
		if (newDecoded.length < decoded.length){
			less_div.html(nl2br(htmlentities(newDecoded)));
			less_div.append(' ..<a href="javascript:void(0)" onclick="$(this).parent().prev().show().prev().show();$(this).parent().hide()">(more)</a>');
			$(this).after(less_div);
			$(this).after('<span> &nbsp;<a href="javascript:void(0)" onclick="$(this).parent().next().show();$(this).parent().hide().prev().hide()">(less)</a></span>');
			$(this).hide().next().hide();
		}
	});
}

function set_gmt_timezone_qfo(){
	var timezone = Math.round(-new Date().getTimezoneOffset()/60*10)/10;
	if (timezone>0){
		timezone = '+'+timezone;
	}
	$('#gmt_timezone').html('GMT '+timezone);
	$('#gmt_timezone').after('<input type="hidden" name="gmt_timezone" value="'+timezone+'"/>');
}


function gmt_translate(){
	var timezone = Math.round(-new Date().getTimezoneOffset()/60*10)/10;
	if (timezone>0){
		timezone = '+'+timezone;
	}	
	$('.gmt_datetime').each(function(){
		var time = strtotime($(this).html().replace(/ GMT$/, ""));
		if (time == false){
			return;
		}
		var new_time = time + timezone*3600;
		$(this).html(date("Y-m-d g:i a", new_time)+ " GMT"+timezone );		
	});
}

function show_tooltips(){
	var tooltips = $(this).attr('data-tips');
	if ($(this).next().size() >0){
		$(this).next().show();
	}else{
		var div_tooltips = $('<div style="position:relative" class="tooltips_parent"><div style="position:absolute" class="tooltips">'+tooltips+'</div></div>');
		$(this).after(div_tooltips);
		div_tooltips.show();
	}
}
function hide_tooltips(){
	$(this).next().hide();
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well

function pageWidth() {
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}



function pageHeight() {
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}


function posLeft() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}


function posTop() {
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;} function posRight() {return posLeft()+pageWidth();} function posBottom() {return posTop()+pageHeight();
}

/////////////////////////////////////////////////////////////
//blockUI functions
/////////////////////////////////////////////////////////////
function blockUI(content, width, height, toBlock){
	content.css('position', 'absolute').addClass('blocking');
	if ( typeof(width) == 'undefined' || width ==0){
		width = parseInt(content.css('width'));
		height =parseInt(content.css('height'));
	}else{
		content.css('width', ''+width+'px').css('height', ''+height+'px');
	}
	content.css('z-index', '10002');
	content.css('left', $('#wrapper').width()/2 - width/2).css('top', posTop()+ (pageHeight()/2) - height/2 -40);
	content.appendTo($('#wrapper'));		
	if (typeof(toBlock) != 'undefined'){
		var block = $('<div style="position: absolute; z-index:10001; background: #ffffff; opacity: 0.6;filter: alpha(opacity=60); left: 0px; top: 0px" class="blocking"></div>');			
		block.width($('#wrapper').width());
		block.height($('#wrapper').height());
		
		block.appendTo($('#wrapper'));		
	}
	content.show();	
}

function unblockUI(){
	$('.blocking').hide();
}

//////////////////////////////////////////////////////////////////
// Overlay functions
//////////////////////////////////////////////////////////////////
function startOverlayTitleCert(title_cert_url, title_cert_name_url, parentIframe){
	var spans_show_title_cert;
	if (parentIframe ==null){
		spans_show_title_cert = $('.show_title_cert');
	}else{
		spans_show_title_cert = $('.show_title_cert', parentIframe);
	}
	spans_show_title_cert.mouseover(function(e){
		var overlay_id = $(this).attr('data-overlay_id');
		if ($('.overlay[data-overlay_id='+overlay_id+']').size()>0){
			$('.overlay[data-overlay_id='+overlay_id+']').attr('data-over', '1');
			return;
		}
		$('.overlay').remove();
		var user_id = $(this).attr('data-user_id');
		var abbrev = $(this).attr('data-abbrev');
		var overlay = $('<div data-overlay_id="'+overlay_id+'" style=" background-image: url(/new_images/front/overlay_cert.gif);" onmouseover="$(this).attr(\'data-over\', \'1\')" onmouseout="unoverlayUI.call(this)"><div style="padding:5px 2px 2px 2px"><table width="100%" border="0" cellpadding="0" cellspaceing="0"><tr><td><div align="center"><a href="'+title_cert_url+'/'+user_id+'/'+abbrev+'/0" target="_blank"><img src="'+title_cert_url+'/'+user_id+'/'+abbrev+'"/></a></div></td></tr><tr><td><div class="profile_title_cert_name" align="center"></div></td></tr></table></div>');
		$('.profile_title_cert_name', overlay).load(title_cert_name_url+'/'+user_id+'/'+abbrev);
		overlayUI(overlay, 152, 230, e.pageX-120, e.pageY - 230 - 10);
	}).mouseout(unoverlayUI);

}
function unoverlayUI(){
	var overlay_id = $(this).attr('data-overlay_id');
	var overlay = $('.overlay[data-overlay_id='+overlay_id+']');
	if (overlay.size()>0){
		overlay.attr('data-over', '0');
		setTimeout(function(){ if (overlay.parent().size()>0 && overlay.attr('data-over')!='1')overlay.remove();}, 500);
	}	
}
function overlayUI(content, width, height, posX, posY){
	content.css('position', 'absolute').addClass('overlay');
	if ( typeof(width) == 'undefined' || width ==0){
		width = parseInt(content.css('width'));
		height =parseInt(content.css('height'));
	}else{
		content.css('width', ''+width+'px').css('height', ''+height+'px');
	}
	content.css('z-index', '10002');
	content.css('left', posX).css('top', posY);
	content.appendTo($('body'));
	content.show();	
}

//////////////////////////////////////////////////////////////////
// Utility functions start
/////////////////////////////////////////////////////////////////

function nl2br( str ) {
    return str.replace(/\n/g, '<br />\n');
}

function rawurlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
	//this line is commented because i want rawurlencode
	//reference to http://www.the-art-of-web.com/javascript/escape/
    //histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };
 
    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();
 
    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function htmlentities( s ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
 
    var div = document.createElement('div');
    var text = document.createTextNode(s);
    div.appendChild(text);
    return div.innerHTML;
}

function html_entity_decode( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
 
    var ret, tarea = document.createElement('textarea');
    tarea.innerHTML = string;
    ret = tarea.value;
    return ret;
}
//////////////////////////////////////////////////////////////////
//
// Note: "april" and "may" is reversed in this strtotime original function ! it sucks!
////////////////////////////////////////////////////////////////

// {{{ strtotime
function strtotime(str, now) {
    // Parse about any English textual datetime description into a Unix timestamp
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strtotime/
    // +       version: 812.3015
    // +   original by: Caio Ariede (http://caioariede.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)
    // *     example 1: strtotime('+1 day', 1129633200);
    // *     returns 1: 1129719600
    // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);
    // *     returns 2: 1130425202
    // *     example 3: strtotime('last month', 1129633200);
    // *     returns 3: 1127041200

    var i, match, s;
    
    str = str.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
    str = str.replace(/[\t\r\n]/g, ''); // unecessary chars

    if (str == 'now') return (new Date()).getTime();
    else if (!isNaN(parse = Date.parse(str))) return parse/1000;
    else if (now) now = new Date(now);
    else now = new Date();

    str = str.toLowerCase();

   var process = function (m) {
        var ago = (m[2] && m[2] == 'ago');
        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);

        switch (m[0]) {
            case 'last':
            case 'next':
                switch (m[1].substring(0, 3)) {
                    case 'yea':
                        now.setFullYear(now.getFullYear() + num);
                        break;
                    case 'mon':
                        now.setMonth(now.getMonth() + num);
                        break;
                    case 'wee':
                        now.setDate(now.getDate() + (num * 7));
                        break;
                    case 'day':
                        now.setDate(now.getDate() + num);
                        break;
                    case 'hou':
                        now.setHours(now.getHours() + num);
                        break;
                    case 'min':
                        now.setMinutes(now.getMinutes() + num);
                        break;
                    case 'sec':
                        now.setSeconds(now.getSeconds() + num);
                        break;
                    default:
                        var day;
                        if (typeof (day = __is_day[m[1].substring(0, 3)]) != 'undefined') {
                            var diff = day - now.getDay();
                            if (diff == 0) {
                                diff = 7 * num;
                            } else if (diff > 0) {
                                if (m[0] == 'last') diff -= 7;
                            } else {
                                if (m[0] == 'next') diff += 7;
                            }

                            now.setDate(now.getDate() + diff);
                        }
                }

                break;

            default:
                if (/\d+/.test(m[0])) {
                    num *= parseInt(m[0]);

                    switch (m[1].substring(0, 3)) {
                        case 'yea':
                            now.setFullYear(now.getFullYear() + num);
                            break;
                        case 'mon':
                            now.setMonth(now.getMonth() + num);
                            break;
                        case 'wee':
                            now.setDate(now.getDate() + (num * 7));
                            break;
                        case 'day':
                            now.setDate(now.getDate() + num);
                            break;
                        case 'hou':
                            now.setHours(now.getHours() + num);
                            break;
                        case 'min':
                            now.setMinutes(now.getMinutes() + num);
                            break;
                        case 'sec':
                            now.setSeconds(now.getSeconds() + num);
                            break;
                    }
                } else {
                    return false;
                }

                break;
        }

        return true;
    };
    
    var __is =
    {
        day:
        {
            'sun': 0, 'mon': 1, 'tue': 2, 'wed': 3,
            'thu': 4, 'fri': 5, 'sat': 6
        },
        mon:
        {
            'jan': 0, 'feb': 1, 'mar': 2, 'apr': 3, 'may': 4,  'jun': 5,
            'jul': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11
        }
    };

    match = str.match(/^(\d{2,4}-\d{2}-\d{2})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);

    if (match != null) {
        if (!match[2]) {
            match[2] = '00:00:00';
        } else if (!match[3]) {
            match[2] += ':00';
        }

        s = match[1].split(/-/g);

        for (i in __is.mon) {
            if (__is.mon[i] == s[1] - 1) {
                s[1] = i;
            }
        }

        return strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]);
    }
 
    var regex = '([+-]?\\d+\\s'
              + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'
              + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'
              + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'
              + '|(last|next)\\s'
              + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'
              + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'
              + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'
              + '(\\sago)?';

    match = str.match(new RegExp(regex, 'g'));

    if (match == null) {
        return false;
    }

    for (i in match) {
        if (!process(match[i].split(' '))) {
            return false;
        }
    }

    return (now);
}// }}}

// {{{ date
function date ( format, timestamp ) {
    // Format a local time/date
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_date/
    // +       version: 901.1301
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: MeEtc (http://yass.meetcweb.com)
    // +   improved by: Brad Touesnard
    // +   improved by: Tim Wiel
    // +   improved by: Bryan Elliott
    // +   improved by: Brett Zamir
    // +   improved by: David Randall
    // *     example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400);
    // *     returns 1: '09:09:40 m is month'
    // *     example 2: date('F j, Y, g:i a', 1062462400);
    // *     returns 2: 'September 2, 2003, 2:26 am'
    // *     example 3: date('Y W o', 1062462400);
    // *     returns 3: '2003 36 2003'
    // *     example 4: x = date('Y m d', (new Date()).getTime()/1000); // 2009 01 09
    // *     example 4: (x+'').length == 10
    // *     returns 4: true

    var a, jsdate=(
        (typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        new Date(timestamp) // Javascript Date()
    );
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];

    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                var t = f.l();
                return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },

        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;

                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{

                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },

        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },

        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            o: function(){
                if (f.n() === 12 && f.W() === 1) {
                    return jsdate.getFullYear()+1;
                }
                if (f.n() === 1 && f.W() >= 52) {
                    return jsdate.getFullYear()-1;
                }
                return jsdate.getFullYear();
            },
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },

        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            u: function(){
                return pad(jsdate.getMilliseconds()*1000, 6);
            },

        // Timezone
            //e not supported yet
            I: function(){
                var DST = (new Date(jsdate.getFullYear(),6,1,0,0,0));
                DST = DST.getHours()-DST.getUTCHours();
                var ref = jsdate.getHours()-jsdate.getUTCHours();
                return ref != DST ? 1 : 0;
            },
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            Z: function(){
               var t = -jsdate.getTimezoneOffset()*60;
               return t;
            },

        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            r: function(){
                return f.D()+', '+f.d()+' '+f.M()+' '+f.Y()+' '+f.H()+':'+f.i()+':'+f.s()+' '+f.O();
            },
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }

        return ret;
    });
}// }}}

function add_follow(id, type){
	$.post('/main/add_follow_'+type, {'id': id},
		function(json){
			if (json.error != null){	
				alert(json.error);
			}else{
				$('#div_follow_btn_'+type+'_'+id).hide();
				$('#div_unfollow_btn_'+type+'_'+id).show();
				$('#span_num_follower_'+type+'_'+id).html(json.num_follower);
			}
		}, 'json');
}

function delete_follow(id, type){
	$.post('/main/delete_follow_'+type, {'id': id},
		function(json){
			if (json.error != null){	
				alert(json.error);
			}else{
				$('#div_follow_btn_'+type+'_'+id).show();
				$('#div_unfollow_btn_'+type+'_'+id).hide();
				$('#span_num_follower_'+type+'_'+id).text(json.num_follower);
			}
		}, 'json');
}

function to_reshare(article_id){
	
	if (user_id <=0){
		alert('Please sign in first');
		return;
		
	}
	var div_to_reshare = $('<div class="popup_box" style="background-color:#FFFFFF;"></div>');
	div_to_reshare.load('/account/blog/to_reshare/'+article_id);
	blockUI(div_to_reshare, 640, 350, true);
}
function to_remove_blog(article_id){
	if (!confirm('Are you sure you want to remove this post?')){
		return;
	}
	$.post('/account/blog/delete_blog', {'article_id': article_id},
		std_ajax_return, 'json');
}


function add_comment_box(prev_box, article_id){
	if (prev_box.siblings('.class_list_comments').size()>0){
		return;
	}

	var options = {
		dataType: 'json',
		success: function(json){
			if (json.error != null){
				alert(json.error);
			}else{
				prev_box.siblings('.class_comment_box').before($(json.msg).html());
				$('.command_line_comment', prev_box).html('Comments('+ json.num_comment +')');
				$('textarea', prev_box.siblings('.class_comment_box')).val('');
			}
		}
	};

	var comment_text = $.ajax({
		type: "POST",
		url: '/main/list_comments/'+article_id,
		async: false
	}).responseText;
	
	comment_text = $(comment_text);
		
	prev_box.after(comment_text);
	$('form', prev_box.siblings('.class_comment_box')).ajaxForm(options);
}

function thank_article(prev_box, article_id){
	if (prev_box.siblings('.class_thank').size()>0){
		return;
	}
	$.post('/account/blog/thank_article', {'article_id': article_id},
		function(json){
			if (json.error != null){
				alert(json.error);
			}else{
				//prev_box.after($('<div class="class_thank" style="padding: 3px; font-size: 12px">You thank this.</div>'));
				$('.command_line_thank', prev_box).html('Thanks('+json.num_thank+')');
			}
		}, 'json');
}

function update_content(){
	var content = FCKeditorAPI.GetInstance('content').GetXHTML();
	$('textarea[name=content]').val(content);

}