
var SS_isProd = (document.domain.indexOf("seesay.com") != -1);
document.domain = SS_isProd?"seesay.com":document.domain;
var SS_ho = SS_isProd?"https://seesay.com":"";
var SS_hoi = SS_isProd?"http://seesay.com":"";

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function SS_jsonp_form (formid, divid) {
	var args = $("#" + formid).serialize();
	SS_jsonp(args, divid);
}

function SS_jsonp (args, divid) {
	var div = $("#" + divid);
	div.html("&nbsp");
    $.ajax({
	  type: "GET",
      url: SS_ho + "/jh?jsonp=?",
	  data: args,
	  dataType: "jsonp",
	  timeout: 10000,
      success: function (result) {
        if (result && result.resultCode) {
				var rc = result.resultCode.toLowerCase();
				if (rc == "failed") {
					var em = result.returnVals.errormessage;
					if (em) {
					    div = $("#" + divid);
						div.html(em);
						return;
					}
				}
				else if (rc == "success") {
					var rp = result.returnVals.redirectpage;
					if (rp) {
						window.location = rp;
					}
				}
		}
      },
      error: function (d, msg) {
	      div = $("#" + divid);
          div.text("SeeSay is down for maintenance.");
      }
    });
}

function SS_updateRT (id, arg) {
	var func = SS_get(id, type_servercheckfunc);
	if (func.length == 0) {
		return;
	}
	var args = {"jsoncommand":func, "arg0":arg};
	$.ajax({
	  type: "GET",
      url: SS_hoi + "/jh?jsonp=?",
	  data: args,
	  dataType: "jsonp",
	  timeout: 5000,
      success: function (result) {
		if (result) {
			var resultCode = result.resultCode;
			if (resultCode) {
				var rc = resultCode.toLowerCase();
				var index = null;
				if (rc == "failed") {
					index = type_taken;
				}
				else if (rc == "success") {
					index = type_available;
				}
				else if (rc == "invalid") {
					index = type_invalid;
				}
				if (index) {
					SS_setErr(id, index);
				}
			}
		}
	 },
	 error: function (d, msg) {
         var yyy = 5;
	 }
	 });
}



var type_errid = 0;
var type_regexp = 1;
var type_invalid = 2;
var type_taken = 3;
var type_available = 4;
var type_servercheckfunc = 5;

// This needs to move to language specific file
var SS_types = {
"choice1":["usernameerr","^([\\w\\.\\-]){3,25}$",
							"Invalid username",
							"Username not available.","Username available!","check_login"],
"passwd1":["passwderr","^.{6,15}$","Invalid password","","",""],
"passwdagain":["passwdagainerr","","Passwords do not match.","","",""],
"email":["emailerr","^[\\w\\.\\-]+@([\\w\\-]+.)+[A-Za-z]{2,6}$",
	"Invalid email","Email already registered","","check_email"],
"fullname":["fullnameerr", "^[\\w\\.\\-\\'@%+ ]{3,50}$",
						"Invalid name",
						"","",""]
};


var SS_recaptcha_shown = false;
var SS_recaptcha_success = false;

function SS_createBtnKeydown () {
	var tf = document.getElementById('recaptcha_response_field');
	if (tf) {
		tf.onkeydown = function(e) {
			// var keyCode = e.keyCode ? e.keyCode : e.which;
			var keyCode = null;
			if (window.event) {
				keyCode = window.event.keyCode;
			}
			if (!keyCode) {
				if (e) {
					keyCode = e.keyCode;
					if (!keyCode) {
						keyCode = e.which;
					}
				}
			}
			if (keyCode && (keyCode == '9')) {
				setTimeout('document.getElementById("registerbtn").focus()', 300);
			}
		};
	}
}

function SS_showRecaptcha () {
    if (!SS_recaptcha_shown && !SS_recaptcha_success) {
		Recaptcha.create("6LclSboSAAAAAJ6FDi1YQMIQOH3H-hTOfpFxwvfx",  "recaptcha", { theme: "white", tabindex: 12 });
		setTimeout('SS_createBtnKeydown()', 100);
		SS_recaptcha_shown = true;
	}
}

function SS_focusRecaptcha () {
	if (SS_recaptcha_shown) {
		Recaptcha.focus_response_field();
	}
}

function SS_get (id, type_index) {
	var arr = SS_types[id];
	return arr[type_index];
}

function SS_setErr (id, err_index) {
    var div = $("#" + SS_get(id, type_errid));
	if (div) {
		if (err_index >= 0) {
		    var errtext = SS_get(id, err_index);
			if (errtext.length > 0) {
				div.text(SS_get(id, err_index));
				return;
			}
		}
		div.html("&nbsp;");
	}
}


function SS_validate (textfield) {                                                
	var id = textfield.id;
	var value = textfield.value;
	SS_showRecaptcha();
	if (id) {
		var pattern = SS_get(id, type_regexp);
		if (pattern) {
			if (value.search(pattern) == -1) {
				SS_setErr(id, type_invalid);
				return;
			}
			else {
				SS_updateRT(id, value);
			}
		}
	}
	SS_setErr(id, -1);
}


function SS_focusOnSubmit (textfield) {
	
}

function SS_validateEmail (textfield) {
	SS_validate(textfield);
}


function SS_comparePwd (textfield, p1) {
	var id = textfield.id;
	var value = textfield.value;
	if (p1 && value) {
		var first = p1.value;
		if (first != value) {
			SS_setErr(id, type_invalid);
			return;
		}
		else {
			SS_setErr(id, -1);
		}
	}
}

function getUrlParams () {
	var urlParams = {};
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q)) {
	   var param = d(e[1]);
       urlParams[param] = d(e[2]);
	}
	return urlParams;
}

window.onload = function () {	
	var lf = "/getmessage?messageid=";
	var index = window.location.href.indexOf(lf);
	if (index > 0) {
		 window.location = fd + window.location.substring(index);
	}
	//---------------------------

	var fd = "http://" + document.domain;
	if ($.cookie('comb') && (!$.cookie('uion') || ($.cookie('uion') == 'f'))) {
		window.location = fd;
	}
	//---------------------------
	
	var urlParams = getUrlParams();
	if (urlParams['code']) {
	    urlParams["jsoncommand"] = "getinfostring";
		SS_jsonp(urlParams, "loginmessage"); 
	}
	//---------------------------
	
    var selected = null;
    var forms = document.forms || [];
    for(var i = 0; i < forms.length; i++){
		var form = forms[i];
        for(var j = 0; j < forms[i].length; j++){
			var input = form[j];
			var tab = input.getAttribute("tabindex");
            if (tab == '101') {
                selected = forms[i][j].focus();
                return;
            }
			else if (tab == '1') {
				selected = forms[i][j];
			}
        }
    }
	if (selected) {
		selected.focus();
	}
	return true;
};



