//外部參數定義
var iTTInit = false;
var year = new Number();
var month = new Number();
var day = new Number();
var hour = new Number();
var min = new Number();
var sec = new Number();
var sfix=0;
var efix=59;
var dStart = new Date();
var fDiff;

$(function() {
	var dLoad = new Date();
	fDiff = dLoad - dStart;
	sec = sec + Math.round( fDiff / 1000 );		   
		   
	Fetchtime();
	loadBannerAds();
});

function Fetchtime()
{
	$.get('iTRYTime.php',function(data,textStatus) {
		if (textStatus != 'success') {
			return false;
		}else {
			var iTT = data;
			t=iTT.split(":");
			year=new Number(t[0]);
			month=new Number(t[1]);
			day=new Number(t[2]);
			hour=new Number(t[3]);
			min=new Number(t[4]);
			sec=new Number(t[5]);
			sfix=0;
			if (!iTTInit) {
				iTTInit = true;
				iTRYTime();
			}
		}
	});
}

function iTRYTime()
{
    sec += 1;
    sfix += 1;
    if (sec >= 60) {
        sec=0;
        min += 1;
    }
	
    if (min >= 60) {
        Fetchtime();
		sfix=0;
    }
	
    if (sfix > efix) {
        Fetchtime();
		sfix=0;
    }
	
	if ( eval( sec ) > 60 ) {
		min = min + Math.floor( sec / 60 );
		sec = sec % 60;
	}
	
	if ( eval( min ) > 60 ) {
		hour = hour + Math.floor( min / 60 );
		min = min % 60;
	}
	
	if ( eval( hour ) > 24 ) {
		hour = hour % 24;
	}
	
    sYear = year;
    sMonth = ( month < 10 ? "0" + month : month );
    sDay = ( day < 10 ? "0" + day : day );
    sHour = ( hour < 10 ? "0" + hour : hour );
    sMin = ( min < 10 ? "0" + min : min );
    sSec = ( sec < 10 ? "0" + sec : sec );
    iTime=sYear+"/"+sMonth+"/"+sDay+"　　　"+sHour+":"+sMin+":"+sSec+"";
	$('#itry-clock').html(iTime);
    window.setTimeout("iTRYTime()",1000);
}

function loadBannerAds()
{
	divEls = document.getElementsByTagName('div');
	adRE = new RegExp( "phpad-[0-9]{1,8}" ); // phpad-(id)
	div_id_params = '';
	
	for( var i=0; i< divEls.length; i++ ) {
		if ( adRE.test( divEls[i].getAttribute('id') ) ) {
			div_id_params = divEls[i].getAttribute('id') + ';' + div_id_params;
		}
	}
	
	if (!document.phpAds_used) {
		document.phpAds_used = ',';
	}
	
	phpAds_random = new String(Math.random());
	phpAds_random = phpAds_random.substring(2,11);
	
	var s;
	s=document.createElement("script");
	s.setAttribute('id',phpAds_random);
	s.setAttribute('type','text/javascript');
	s.setAttribute('src','http://ads.itry.com.tw/v1/loadalladjs.php?n='+phpAds_random+'&exclude='+document.phpAds_used+'&charset='+(document.charset || document.characterSet)+(document.referrer?'&referer='+escape(document.referrer):'') + '&div_id=' + div_id_params);
	
	var head=document.getElementsByTagName("head")[0];
	head.appendChild(s);
}

/* popup window */
function popWin( url, winame, wintype, override_extras ) 
{
    if( typeof wintype != "string" ) { wintype = ""; }
    switch( wintype )
    {
        case 'playMovie': extras = 'scrollbars=no,resizable=no,width=640,height=480,left=20,top=20,status=yes'; break;
        case 'doVote': extras = 'scrollbars=no,resizable=no,width=600,height=560,left=20,top=20,status=yes'; break;
        case 'doForward': extras = 'scrollbars=no,resizable=no,width=600,height=720,left=20,top=20,status=yes'; break;
        case 'showNote': extras = 'scrollbars=no,resizable=no,width=680,height=630,left=20,top=20,status=yes'; break;
        case 'playMusic': extras = 'scrollbars=no,resizable=no,width=240,height=100,status=yes'; break;
        case 'info': extras = 'scrollbars=no,resizable=no,width=600,height=580,status=yes'; break;
		case 'print': extras = 'scrollbars=yes,resizable=yes,width=600,height=580,status=yes,menubar=yes'; break;
        case 'override': extras = override_extras; break;
        default: extras = 'scrollbars=yes,width=620,height=420,resizable=yes,status=yes';
    }
    myPop = window.open( url, winame, extras );
    myPop.focus();
}

/***** Validator class *****/
var Validator = new Object();

/* regular expressions */
Validator.RE = new Object();
Validator.RE.email = /^[_\.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,6}$/;
Validator.RE.tel = /^[0-9 \(\)\-]{6,16}$/;
Validator.RE.img_ext = /(\.jpg|\.JPG|\.gif|\.GIF|\.jpeg|\.JPEG)$/;
Validator.RE.audio_ext = /(\.wav|\.WAV|\.mp3|\.MP3)$/;

/* checkString : boolean */
Validator.checkString = function( str, min_len, max_len, chktype )
{
    if( typeof chktype != "string" ) { chktype = ""; }
    if( typeof str != "string" )
    { alert( "Validator.checkString error: non-string provided" ); return false; }
    // trim the string!
    str = $.trim( str );
    if( min_len == 0 && str.length == 0 ) { return true; }
    if( str.length < min_len ) { return false; }
    if( str.length > max_len ) { return false; }
    switch( chktype )
    {
        case 'email':
            return Validator.RE.email.test(str);
            break;
        
        case 'safe-ascii': // ascii chars except non-printing ones
            for( var i=0; i<str.length; i++ )
            { if( str.charCodeAt(i)>125 || str.charCodeAt(i)<32 ) return false; }
            break;
        
        case 'non-english':
            for( var i=0; i<str.length; i++ )
            { if( str.charCodeAt(i)<128 ) return false; }
            break;
            
        case 'tw-pid': // Personal ID (Taiwan)
            var c, n, i;
            var t = "ABCDEFGHJKLMNPQRSTUVXYWZIO";
            var s = str;
            c = s.substring(0,1);
            c = t.indexOf(c.toUpperCase());
            if ((s.length!= 10) || (c<0)) return false;
            n = parseInt(c/10)+ c%10*9+ 1;
            for (var i=1; i<9; i++) n = n + parseInt(s.substring(i,i+1))* (9-i);
            n = (10- (n% 10))% 10;
            if (n != parseInt(s.substring(9,10))) return false;
            break;
        
        default: // only check length, which is done above
            break;
    }   // end switch
    return true;
}   // end Validator.checkString()

/* checkNumber : boolean */
Validator.checkNumber = function( num, min, max, chktype )
{
    if( isNaN(num) ) { return false; }
    switch( chktype )
    {
        case 'float':
            return ( num >= min && num <= max ); 
            break;
            
        case 'int':
        default:
            if( !(/^[0-9]+$/.test(num) ) ) { return false; }
            else { return ( num >= min && num <= max ); }
            break;
    }
    return true;
}


/***** Form Validation *****/
/*
grabs values from the "required" hidden field
*/
Validator.genericFormChecker = function( formObj )
{
    if( !isDom ) { return true; }
    // no "required" field specified
    if( !formObj.required ) return true;
    var warnings = "";
    // sample "required" field value="username,名字,3,24|gender,性別|city|email,E-mail,10,128,email"
    var req_fields_arr = formObj.required.value.split("|");
    for( var i=0; i<req_fields_arr.length; i++ )
    {
        var field_params_arr = req_fields_arr[i].split(",");
        var field_name = field_params_arr[0];
        var field_label = (field_params_arr[1]) ? field_params_arr[1] : field_name;
        if( !formObj.elements[field_name] )
        { alert("Validator.genericFormChecker Error:\nNot a form element: "+field_name); }
        var ele = formObj.elements[field_name];
        // alert( field_name + " is of type: " + ele.type +", with "+ele.length+" sub elements." );
        // do things according to field type
        switch( ele.type )
        {
            case 'text':
            case 'textarea':
                var min_len = (field_params_arr[2]) ? field_params_arr[2] : 0;
                // max length is optional and will be derviced from "required" param, maxlength attribute or hard coded (216)
                var max_len = (field_params_arr[3]) ? field_params_arr[3] : (ele.maxLength) ? ele.maxLength : 216;
                var chktype = (field_params_arr[4]) ? field_params_arr[4] : ""; // eg. "email"
                if( chktype == "int" || chktype == "float" )
                {
                    if( !Validator.checkNumber( ele.value, min_len, max_len, chktype ) )
                    { warnings += "\n- " + field_label; }
                }
                else if( !Validator.checkString( ele.value, min_len, max_len, chktype ) )
                { warnings += "\n- " + field_label; }
                break;
            
            case 'select-one':
                // just check if selected value is empty or not
                // due to IE's inability to automatically fill-in "text" as the value when
                // none has been specified
                if( ele.options[ele.selectedIndex].value == "" && ele.selectedIndex == 0 )
                { warnings += "\n- " + field_label; }
                break;
            
            case 'select-multiple':
                // not sure what to check for just yet
                break;
            
            case 'checkbox':
                // if specified, must be checked
                if( !ele.checked )
                { warnings += "\n- " + field_label }
                break;
            
            case 'file':
                if( ele.value == "" )
                { warnings += "\n- " + field_label; }
                break;
            
            case 'password': // only check for length
                var min_len = (field_params_arr[2]) ? field_params_arr[2] : 0;
                // max length is optional and will be derviced from "required" param, maxlength attribute or hard coded (216)
                var max_len = (field_params_arr[3]) ? field_params_arr[3] : (ele.maxLength) ? ele.maxLength : 216;
                var chktype = (field_params_arr[4]) ? field_params_arr[4] : ""; // eg. "email"
                if( !Validator.checkString( ele.value, min_len, max_len, chktype ) )
                { warnings += "\n- " + field_label; }
                break;
            
            default: // most likely radio group
                // determine whether this is a group of radio buttons
                if( typeof ele.length != "undefined" && ele[0].type == "radio" )
                {   // there's more than one
                    var radio_checked = 0;
                    for( var j=0; j<ele.length; j++ )
                    { if( ele[j].checked ) { radio_checked++; } }
                    if( radio_checked < 1 )
                    { warnings += "\n- " + field_label; }
                }
        }   // end switch
    
    }   // end for
    if( warnings.length > 1 )
    {
        alert( "Please make sure the following fields are correct:\n" + warnings );
        return false;
    }
    return confirm( "Are you sure you wish to proceed?" );
    
}

/*
attach form checkers
according to the "name" attribute specified
*/

Validator.attachFormCheckers = function()
{
    if( !isDom ) return;
    var formObjs = document.getElementsByTagName( "form" );
    for( var i=0; i<formObjs.length; i++ )
    {
        switch( formObjs[i].name )
        {
            /*
            case 'dashboardIssueListForm':
                addOnSubmitEvent( formObjs[i], function(){this.page.value=''; return Dashboard.listIssues(this)} );
                break;
            */
			
            default: // attach generic form checker
                if( formObjs[i].elements['required'] )
                { addOnSubmitEvent( formObjs[i], function(){return Validator.genericFormChecker(this)} ); }
                break;
        }
    }
}
/**/


function get_new_code()
{
	$('#codeImage').attr("src","lib/genpnc.php?n="+Math.random());
}

