﻿function confirmAction(url, msg) {
	if (msg != '')	{
		if (confirm(msg)) {
			document.location.href = url;
		}
		return;
	}
	location.href = url;
}
function dateDiff(date1,date2,interval) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            ( date2.getFullYear() * 12 + date2.getMonth() )
            -
            ( date1.getFullYear() * 12 + date1.getMonth() )
        );
        case "weeks"  : return Math.floor(timediff / week);
        case "days"   : return Math.floor(timediff / day);
        case "hours"  : return Math.floor(timediff / hour);
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        default: return undefined;
    }
}
function stripTags(str, option) {
    str = str.replace(/&nbsp;/g,'');
	str = jQuery.trim(str);
	if( option == 'comment_vhome' )
		allowed_tags = '<a>';
	else if( option == 'comment' )
		allowed_tags = '<a><img>';
	else if( option == 'question' )
		allowed_tags = '<a>';
	else if( option == 'mail' )
		allowed_tags = '<a><img>';
	else if( option == 'blog' )
		allowed_tags = '<a><img>';
	else if (option == 'faq')
		allowed_tags = '<font>';
	else if (option == 'getlink')
		allowed_tags = '<embed><object><param>';
	else allowed_tags = '';
	var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
    str += '';
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}
function roundNumber(rnum, rlength) {
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber;
}
function isValidImage(strFilename) {
  var ext = (strFilename.substring(strFilename.length-4, strFilename.length)).toLowerCase();
  ext = ext.replace('.', '');
  if( ext != 'jpg' && ext != 'gif' && ext != 'png' && ext != 'jpeg' ) return false;
  return true;
}
function isValidFlash(strFilename) {
  var ext = (strFilename.substring(strFilename.length-4, strFilename.length)).toLowerCase();
  ext = ext.replace('.', '');
  if( ext != 'swf') return false;
  return true;
}
function isValidDate(dateStr, format) {
	if (format == null) { format = "MDY"; }
	format = format.toUpperCase();
	if (format.length != 3) { format = "MDY"; }
	if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
	if (format.substring(0, 1) == "Y") {
	  var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
	  var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
	} else if (format.substring(1, 2) == "Y") {
	  var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
	  var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
	} else {
	  var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
	  var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	}
	if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
	var parts = dateStr.split(RegExp.$1);
	if (format.substring(0, 1) == "M") { var mm = parts[0]; } else if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
	if (format.substring(0, 1) == "D") { var dd = parts[0]; } else if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
	if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
	if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
	if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
	var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
	if (parseFloat(dd) != dt.getDate()) { return false; }
	if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
	return true;
}
function isPhoneNumber(str){
	var alphaExp = /^((\(\+?84\)[\-\.\s]?)|(\+?84[\-\.\s]?)|(0))((\d{3}[\-\.\s]?\d{6})|(\d{2}[\-\.\s]?\d{8}))$/;
	if(str.match(alphaExp)){
		return true;
	}
	return false;
}
function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
function isAlphabet(str){
	var alphaExp = /^[a-zA-Z]+$/;
	if(str.match(alphaExp)){
		return true;
	}
	return false;
}
function isAlphabetAndNumber(str) {
	var alphaExp = /^[a-zA-Z0-9_]+$/;
	if (str.match(alphaExp)){
		return true;
	}
	return false;
}
function isNumber(str) {
	var alphaExp = /^[0-9]+$/;
	if(str.match(alphaExp)){
		return true;
	}
	return false;
}
function checkAll(strItemName, value) {
	var x=document.getElementsByName(strItemName);
	for (var i=0; i<x.length; i++) {
	  	if (value == 1) {
			if( !x[i].checked ) x[i].checked = 'checked';
		} else {
			if(x[i].checked) x[i].checked = '';
		}
	}
}
function getItemsChecked(strItemName, sep) {
	var x=document.getElementsByName(strItemName);
	var p="";
	for(var i=0; i<x.length; i++) {
		if(x[i].checked) {
			p += x[i].value + sep;
		}
	}
	var result = (p != '' ? p.substr(0, p.length - 1) : '');
	return result;
}
function setItemsChecked(strItemName) {
	vnc_setCookie( strItemName, getItemsChecked(strItemName) );
}
function vnc_setCookie( name, value, expires) {
	// set time, it's in milliseconds
	var domain = '.'+DOMAIN;
	var path = '/';
	var secure = '';
	var today = new Date();
	today.setTime( today.getTime() );
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires==undefined) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
function vnc_getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	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++) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		// if the extracted name matches passed check_name
		if  (cookie_name == check_name) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return null;
	}
}
function closeUI() {
	$.unblockUI();
}
function vnc_deleteCookie(name) {
	vnc_setCookie(name, '',  315554400);
}
function addError(txt, msg) {
	var span = document.createElement("span");
	span.className = "ErrorMessage";
	span.innerHTML = msg;
	span.insertAfter($('#' + txt));
}
function onsubmitLogin() {
	var strEmail = $("#txtEmailLogin").val();
	var strPassword = $("#txtPasswordLogin").val();
	if( strEmail == '' || strPassword == '' )
	{
		return false;
	}
}
function showUIMessage(msg) {
	if (msg!='') {
		$.blockUI({message: msg, css: {background:'#fffbba', color:'#a90a0e', border:'1px solid #ffc407', showOverlay: false, width:'300px', top: ($(window).height()-200)/2 + 'px', left:($(window).width()-300)/2 + 'px', padding:'10px'}, overlayCSS: {opacity:'0'}});
		$('.blockOverlay').click($.unblockUI);
		setTimeout($.unblockUI, 2*20*60);
	}
}
function submitAction(formName, actionForm){
	var frm = document.forms[formName] ;
	frm.action	= actionForm;
	frm.submit();
}
function page(offset, url, div) {
	if(offset==undefined) offset=0;
	if(url==undefined) url='';
	if(div==undefined) div='';
	$.get(url+'offset='+offset,{},function(result){if(result){$('#'+div).html(result);}});
}
function paging(url, div) {
	/* if(offset==undefined) offset=0;
	if(url==undefined) url='';
	if(div==undefined) div=''; */
	$.get(url,{},function(result){if(result){$('#'+div).html(result);}});
}
function paging2(url, div) {	
	$.ajax({
		cache	: false,
		async	: false,
		data	: null,
		url		: url,
		dataType: 'jsonp',
		jsonp	: 'callback',
		success	: function(response) {
			$('#'+div).html(response);
		}
	});
}
validateCaptcha = function (pinput, pdomain) {
	var result = false; 
	if (pinput.length == 6) {
		if (pdomain== undefined || pdomain == 'default') HOST = HOST_ACL;
		else HOST = 'http://' + pdomain + '.' + DOMAIN + '/';
		var strUrl = HOST + 'valid/isvalidcaptcha';
		$.ajax({
			cache	: false,
			async	: false,
			type	: 'POST',
			data	: 'input='+pinput,
			url		: strUrl,
			success	: function(response) {
				result = (response == '1' ? true : false);
			}
		});
	}
	return result;
}
refreshCaptcha = function (pcontainer, pdomain, psession) {
	if (psession == undefined) psession = '';
	if (pdomain == undefined || pdomain == 'default') HOST = HOST_ACL;
	else HOST = 'http://' + pdomain + '.' + DOMAIN + '/';
	var strUrl = HOST + 'ajax/refreshcaptcha';
	$.ajax({
		cache	: false,
		async	: false,
		type	: 'POST',
		data	: 'container='+pcontainer + '&amp;session='+psession + '&amp;domain='+pdomain,
		url		: strUrl,
		success	: function(response) {
			$('#'+pcontainer).html(response);
		}
	});
}

isValidEmail = function(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

allValidChars = function(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}
uilogin = function() {
	var purl = HOST_API+'uilogin';
	$.ajax({
		cache	: false,
		async	: false,
		data	: null,
		url		: purl,
		dataType: 'jsonp',
		jsonp	: 'callback',
		success	: function(response) {
			$.blockUI({
			message: response,
				css: {
					border: 'none',
					width: 300+'px',
					top:  ($(window).height() - 300)/2 + 'px',
					left: ($(window).width() - 300)/2 + 'px',
					cursor: 'pointer'
				}
			});
		}
	});
}
checkwebsite = function (str) {
	var re=/^[\w-]+([\w-]+\.)+[a-zA-Z]{2,4}$/
	var re1=/^http:\/\/[\w-]+([\w-]+\.)+[a-zA-Z]{2,4}$/
	if (str.match(re)) {
		return true
	} else if (str.match(re1)) {
		return true
	}
	return false;
}
function new_Array(rows) {
  var arr = [];
  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }
  return arr;
}
function in_Array(a, v) {
	if (a.length > 0) {
		for (var i = 0; i < a.length; i++) {
			if (a[i] == v) return 1;
		}
	}
	return 0;
}
if (strMsg) showUIMessage(strMsg);
if (strErr) alert(strErr);
function addbm() {
	var e1=document.createElement('input');
	e1.setAttribute('type','hidden');
	e1.setAttribute('id','bookmarklet_base_url_id');
	e1.setAttribute('value','http://aicoly.dev');
	document.body.appendChild(e1);
	var e=document.createElement('script');
	e.setAttribute('type','text/javascript');
	e.setAttribute('src','http://static.aicoly.dev/js/bookmarklet.js');
	document.body.appendChild(e);
}
