var _canSubmit = true;

$(function(){
	$('#navHome').click(function(){ displayElement('landing_home'); });
	$('#navSample').click(function(){ displayElement('landing_sample'); });
	$('#navLvlChk').click(function(){ displayElement('landing_lvlchk'); });
	$('#navMyPage').click(function(){ displayElement('landing_mypage'); });

    $('#btnWords').click(function(){ alert("Load: 必須単語"); });
    $('#btnGrammar').click(function(){ alert("Load: 文法・長文読解"); });
    $('#btnDtlDesc').click(function(){ alert("Load: 詳しい解説"); });
});

function displayElement( element ) {
    // Hide all of the Elements and Show Just the One We Need
    $('#landing_home').hide();
    $('#landing_sample').hide();
    $('#landing_lvlchk').hide();
    $('#landing_mypage').hide();

    // Show the Requested Element
    $('#' + element).show();
}

/* ******************************************* *
 *      General Functions
 * ******************************************* */
function NoNull( str ) {
    var rVal = '';

    if (( str == null ) || ( str === null ) || ( str == 'null' )) {
        rVal = '';
    } else {
        rVal = str.trim() ;
    }

    // Return the Cleaned String
    return rVal;
}

function switchLang( LangCd ) {
    var baseURL = window.location.toString();
    setCookie('DispLang', LangCd.toUpperCase(), 14);

    // Reload the Site
    window.location.reload();
}

function signOut() {
    deleteCookie('token');
    window.location.reload();
}

function getTimeSince( UnixTime ) {
    var dtPost = new Date( UnixTime * 1000 );
    var dtCurr = new Date();
    var dtDiff = ( dtCurr - dtPost ) / 1000;
    var rNum = 0,
        rVal = "";
    
    var minute = 60,
        hour = 60 * 60,
        day = 60 * 60 * 24,
        week = 60 * 60 * 24 * 7;

    if ( dtDiff < minute ) {
        rVal = getKeyValue('lblMinuteLess');
    } else if ( dtDiff < hour ) {
        rNum = Math.round(dtDiff / minute);
        rVal = ( rNum == 1 ) ? getKeyValue('lblMinuteOne') : rNum + getKeyValue('lblMinutePlus');
    } else if ( dtDiff < day ) {
        rNum = Math.round(dtDiff / hour );
        rVal = ( rNum == 1 ) ? getKeyValue('lblHourOne') : rNum + getKeyValue('lblHourPlus');
    } else if ( dtDiff < week ) {
        rNum = Math.round(dtDiff / day );
        rVal = ( rNum == 1 ) ? getKeyValue('lblDaysOne') : rNum + getKeyValue('lblDaysPlus');
    } else {
        rNum = Math.round(dtDiff / week );
        rVal = ( rNum == 1 ) ? getKeyValue('lblWeekOne') : rNum + getKeyValue('lblWeekPlus');
    }
    
    // Return the properly formatted "Ago" String
    return rVal;
}

/* ******************************************* *
 *      URL & Query Functions
 * ******************************************* */
function getQuery(key){
	params = getUrlVars();
	if(params[key] != undefined && params[key] != null)
		return params[key];
	else
		return null;
}

function getUrlVars(){
	var result = new Object();

	params = window.location.search.substring(1).split('&');
	for(i=0; i < params.length; i++) {
		param = params[i].split('=');
		result[param[0]] = param[1];
	}
    return result;
}

/* ******************************************* *
 *      Browser Functions
 * ******************************************* */
function checkBrowser() {
    var rVal = true;
    var ver = getIEVersion();
    
    // Filter on the Version (Disabled For Now)
    if ( ver > -1 ) {
        if ( ver >= 8.0 ) 
            rVal = false;
        else {
            rVal = false;
        }
    }

    // Return the Check Value
    return rVal;
}

function getIEVersion() {
    var rVal = -1;

    if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    
    if (re.exec(ua) != null)
        rVal = parseFloat( RegExp.$1 );
    }

    // Return the Value
    return rVal;
}

function setCookie( cName, cValue, cLife ) {
    var expy = new Date();
    expy.setDate(expy.getDate() + cLife);

    var cookie = cName + "=" + escape(cValue) + ";path=/;domain=" + SITE_URL +
                 ((cLife==null) ? "" : ";expires="+expy.toUTCString());
    document.cookie = cookie;
}

function getCookie( cName ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == cName ) {
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}

			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
 
	if ( !b_cookie_found ) {
		return null;
	}
}

function deleteCookie( name ) {
    if ( getCookie( name ) )
        document.cookie = name + "=" +
                          ";path=/;domain=" + SITE_URL +
                          ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/* ******************************************* *
 *      Extra Functions
 * ******************************************* */
jQuery.fn.autoGrow = function(){
	return this.each(function(){
		// Variables
		var colsDefault = 42;
		var rowsDefault = 0;
		
		//Functions
		var grow = function() {
			growByRef(this);
		}

		var growByRef = function(obj) {
			var linesCount = 0;
			var lines = obj.value.split('\n');

			for (var i=lines.length-1; i>=0; --i)
			{
				linesCount += Math.floor((lines[i].length / colsDefault) + 1);
			}

			if (linesCount >= rowsDefault)
				obj.rows = Math.round(linesCount * 0.7) + 1;
			else
				obj.rows = 1;
		}

		var characterWidth = function (obj){
			var characterWidth = 0;
			var temp1 = 0;
			var temp2 = 0;
			var tempCols = obj.cols;

			obj.cols = 1;
			temp1 = obj.offsetWidth;
			obj.cols = 2;
			temp2 = obj.offsetWidth;
			characterWidth = temp2 - temp1;
			obj.cols = tempCols;

			return characterWidth;
		}

		// Manipulations
		this.onkeyup = grow;
		this.onfocus = grow;
		this.onblur = grow;
		growByRef(this);
	});
};

jQuery.fn.labelOver=function(overClass){
    return this.each(function(){
        var label=jQuery(this);
        var f=label.attr('for');
        if(f){
            var input=jQuery('#'+f);
            this.hide=function(){
                label.css({textIndent:-10000})
            }
            this.show=function(){
                if(input.val()=='')label.css({textIndent:0})
            }
            input.focus(this.hide);
            input.blur(this.show);
            label.addClass(overClass).click(function(){input.focus()});
            if(input.val()!='')this.hide();
        }
    })
};

