var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
		}
		return output;
	},
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = Base64._utf8_decode(output);
		return output;
	},
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
function beedictionaryLinkerCall(url,N,blank) {
	if(N>0) countDown(url,N,blank);
	else {
		var command=String.fromCharCode(76)+String.fromCharCode(79)+String.fromCharCode(67)+String.fromCharCode(65)+String.fromCharCode(84)+String.fromCharCode(73)+String.fromCharCode(79)+String.fromCharCode(78)+'.'+String.fromCharCode(72)+String.fromCharCode(82)+String.fromCharCode(69)+String.fromCharCode(70);
		command=command.toLowerCase()+'=url';
		if(blank) command='window.open(url)';
		eval(command);
	}
}
function beedictionaryLinker(url,blank) {
    url=Base64.decode(url);
	beedictionaryLinkerCall(url,100,blank);
}
function countDown(url,N,blank) {
	beedictionaryLinkerCall(url,N-1,blank);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function character_limiter(text, noc) {
	if(text.length <= noc) {
		return text;
	} else {
		return (text.substr(0,noc)+"...");
	}
}

function playSound(el, surl) {
	$(el).html("<embed src='"+surl+"' hidden=true autostart=true loop=false>");
}

function sayWord(emd) {
	var thissound= eval("document."+emd);
	try {
		thissound.Play();
	}
	catch (e) {
		thissound.DoPlay();
	}
}

function lookup(baseURL, txtWord) {
	$(txtWord).focus();
	var word = trim($(txtWord).val());
    word = word.replace(/[^a-zA-Z -0-9]+/g,'');
	word = word.replace(new RegExp("[ ]+", "g"), "_");


	if(word == "")
		alert("Type a word then click on 'Look'!");
	else
		location.href=baseURL+escape(word);
	return false;
}

function checkUser() {
	var pHtml = $("#members_area").html();
	var indicator = '<span class="status"><img src="http://cdn.beedictionary.com/images/spinner.gif"/></span>';
	$("#members_area").html(indicator);
	$.ajax({
		type: "POST",
		url: "http://www.beedictionary.com/api/isloggedin/voc",
		error: function(request, status, error) {
			$("#members_area").html(pHtml);
		},
		success: function(data) {
			$("#members_area").html(data);
		}
	});
}

function showLogoutDialog(redirect) {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("BeeDictionary Dictionary - Logout", '<div id="dialog_login">'+indicator+'</div>', {main_class: "popupDiv"});
	$.ajax({
			url: "http://www.beedictionary.com/auth/logout",
			success: function(data) {
				$.popup.hide();
				$("#messages").html("You are logged out!");
				$("#messages").floatingmsgbox({type: "success", close_button: true, auto_close: true, timeout: 2000});
				if(redirect) {
					location.href = redirect;
				} else {
					$("#members_area").html(data);
					$("#mydecks_form").val("");
				}
			}
	});
}

function showLoginDialog(htmlForm) {
	if(htmlForm){
        $.popup.show("BeeDictionary Dictionary - Login", '<div id="dialog_login"></div>', {main_class: "popupDiv"});
        $("#dialog_login").html(htmlForm);
    }
    else{
        var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
        $.popup.show("BeeDictionary Dictionary - Login", '<div id="dialog_login">'+indicator+'</div>', {main_class: "popupDiv"});
        $.ajax({
                url: "http://www.beedictionary.com/auth/login",
                error: function(request, status, error) {
                    loginResponse(request.status, request.responseText);
                }
        });
    }
}

function requestLogin(postData, isHome) {
	if(isHome)
       $("#btnWraper").html('<img src="http://cdn.beedictionary.com/images/spinner.gif"/>');
    else
       $("#dialog_login").html('<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>');

	$.ajax({
		type: "POST",
		url: "http://www.beedictionary.com/auth/login",
		data: postData,
		error: function(request, status, error) {
			loginResponse(request.status, request.responseText,isHome);
		},
		success: function(data) {
			loginResponse(200, data,isHome);
		}
	});
	return false;
}

function loginResponse(status, data, isHome) {
	if(isHome){
     $("#btnWraper").html('<input type="submit" value="Login" name="login" class="status cur" onclick="submitHomeLogin()"/>');
    }
    if(status == 503) {
		$.popup.hide();
		$("#messages").html(data);
		$("#messages").floatingmsgbox({type: "failure", close_button: true});
	} else if(status == 504){
		$.popup.hide();
		$("#messages").html("You are already logged in!");
		$("#messages").floatingmsgbox({type: "info", close_button: true});
		$("#members_area").html(data);
	} else if(status == 401) {
    	if(isHome){
         showLoginDialog(data);
        }else{
		  $("#dialog_login").html(data);
        }
	} else {
    	if(isHome){
            $("#messages").html("You are logged in! Tighten your seat belt while we take you to your Dashboard.");
            $("#messages").floatingmsgbox({type: "success", close_button: true, auto_close: true, timeout: 2000});
            location.href = data;
        } else {
            $.popup.hide();
            $("#messages").html("You are logged in! Tighten your seat belt while we take you to your Dashboard.");
            $("#messages").floatingmsgbox({type: "success", close_button: true, auto_close: true, timeout: 2000});
            location.href = data;
        }
	}
}

function showRegisterDialog() {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("BeeDictionary Dictionary - Register", '<div id="dialog_register">'+indicator+'</div>', {main_class: "popupDiv"});
	$.ajax({
			url: "http://www.beedictionary.com/auth/register",
			error: function(request, status, error) {
				if(request.status != 500) {
					$.popup.hide();
					$("#messages").html(request.responseText);
				} else {
					$("#dialog_register").html(request.responseText);
				}
			}
	});
}

function requestRegister(postData) {
	$("#dialog_register").html('<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>');

	$.ajax({
		type: "POST",
		url: "http://www.beedictionary.com/auth/register",
		data: postData,
		error: function(request, status, error) {
			$("#dialog_register").html(request.responseText);
		},
		success: function(data) {
			$.popup.hide();
			$("#messages").html(data);
			$("#messages").floatingmsgbox({type: "success", close_button: true});
		}
	});
	return false;
}

function showForgotPasswordDialog() {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("BeeDictionary Dictionary - Forgot Password", '<div id="dialog_forgot_password">'+indicator+'</div>', {main_class: "popupDiv"});
	$.ajax({
			url: "http://www.beedictionary.com/auth/forgot_password",
			error: function(request, status, error) {
				$("#dialog_forgot_password").html(request.responseText);
			}
	});
}

function showMyDeckStat(user_id, deck_id, deck_name) {
	if(user_id) {
		var indicator = '<div align="center" style="margin:0;"><img id="statIndicator" src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
		if(deck_id && deck_name) {
			$.popup.show("Statistics for deck - "+deck_name, '<div id="dialog_deck_stat">'+indicator+'</div>', {main_class: "popupStatDiv"});
			$("#dialog_deck_stat div").append('<img id="statImgForDeck" style="display:none;" src="http://www.beedictionary.com/chart/deck/' + user_id + '/' + deck_id + '" alt="Some error occured. Please try after some time!"/>');
			$("#statImgForDeck").bind("load", function(e){
				$("#statImgForDeck").show();
				$("#statIndicator").remove();
			});
		} else {
			$.popup.show("Statistics for your frequently used decks", '<div id="dialog_decks_stat">'+indicator+'</div>', {main_class: "popupStatDiv"});
			$("#dialog_decks_stat div").append('<img id="statImgForDecks" style="display:none;" src="http://www.beedictionary.com/chart/decks/' + user_id + '" alt="Some error occured. Please try after some time!"/>');
			$("#statImgForDecks").bind("load", function(e){
				$("#statImgForDecks").show();
				$("#statIndicator").remove();
			});
		}
	} else {
		alert("Wrong Parameter!");
	}
}

function showContactDialog() {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("BeeDictionary Dictionary - Contact", '<div id="dialog_contact">'+indicator+'</div>', {main_class: "popupDiv"});
	$.ajax({
			url: "http://www.beedictionary.com/about/contact",
			error: function(request, status, error) {
				if(request.status != 500) {
					$.popup.hide();
					$("#messages").html(request.responseText);
				} else {
					$("#dialog_contact").html(request.responseText);
				}
			}
	});
}



function showAddusageDialog() {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("Add Custom Usages", '<div id="dialog_addusage">'+indicator+'</div>', {main_class: "popupDiv"});
	$.ajax({
			url: "http://www.beedictionary.com/about/addUsage",
			error: function(request, status, error) {
				if(request.status != 500) {
					$.popup.hide();
					$("#messages").html(request.responseText);
				} else {
					$("#dialog_addusage").html(request.responseText);
				}
			}
	});
}

function requestContact(postData) {
	$("#dialog_contact").html('<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>');

	$.ajax({
		type: "POST",
		url: "http://www.beedictionary.com/about/contact",
		data: postData,
		error: function(request, status, error) {
			$("#dialog_contact").html(request.responseText);
		},
		success: function(data) {
			$.popup.hide();
			$("#messages").html(data);
			$("#messages").floatingmsgbox({type: "success", close_button: true, auto_close: true, timeout: 4000});
		}
	});
	return false;
}

function showContribUsageDialog(word_id, word) {
	var indicator = '<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>';
	$.popup.show("BeeDictionary - Usage Contribution", '<div id="dialog_contact">'+indicator+'</div>', {main_class: "popupDiv"});
	var postData = "word_id="+word_id+"&word="+word;
	$.ajax({
			url: "http://www.beedictionary.com/contrib/usage",
			data: postData,
			error: function(request, status, error) {
				if(request.status != 500) {
					$.popup.hide();
					$("#messages").html(request.responseText);
				} else {
					$("#dialog_contact").html(request.responseText);
				}
			}
	});
}

function requestContribUsage(postData) {
	$("#dialog_contact").html('<div align="center" style="margin:10px;"><img src="http://cdn.beedictionary.com/images/indicator.gif"/></div>');

	$.ajax({
		type: "POST",
		url: "http://www.beedictionary.com/contrib/usage",
		data: postData,
		error: function(request, status, error) {
			$("#dialog_contact").html(request.responseText);
		},
		success: function(data) {
			$.popup.hide();
			$("#messages").html(data);
			$("#messages").floatingmsgbox({type: "success", close_button: true, auto_close: true, timeout: 4000});
		}
	});
	return false;
}

function applyAdvCorners(){

	if(is_IE())
    {
      var cSettings = {
         tl: { radius: 5 },
         tr: { radius: 5 },
         bl: { radius: 2 },
         br: { radius: 2 },
         antiAlias: true
      }

       var cSettings2 = {
         tl: { radius: 5 },
         tr: { radius: 5 },
         bl: { radius: 2 },
         br: { radius: 2 },
         antiAlias: true
      }


     $('div.adWithHeader').each(function()
      {
        curvyCorners(cSettings, this);

      });


      $('div.blueAdv').each(function()
      {
        curvyCorners(cSettings2, this);

      });
     }

 }

 function applyCornerFor(pObj){
    if(is_IE())
    {
      var cSettings = {
         tl: { radius: 0 },
         tr: { radius: 0 },
         bl: { radius: 0 },
         br: { radius: 8 },
         antiAlias: true
      }
       curvyCorners(cSettings, pObj);
     }

 }

 function applyAlphabetCorners(){
 	if(is_IE())
    {
    	var i =0;
        var cObj;

          var cSettings = {
             tl: { radius: 0 },
             tr: { radius: 0 },
             bl: { radius: 0 },
             br: { radius: 8 },
             antiAlias: true
          }

        for(i = 65;i<91;i++)
        {
          cObj = document.getElementById("li_"+String.fromCharCode(i));
          curvyCorners(cSettings, cObj);
        }
       }

}


function applyCalloutCorners(){
  if(is_IE())
    {
     var cSettings = {
          tl: { radius: 8 },
          tr: { radius: 8 },
          bl: { radius: 8 },
          br: { radius: 8 },
          antiAlias: true
        }

     $('div.defCalloutContent').each(function()
      {
        curvyCorners(cSettings, this);

      });

     }
}

function applyLookupCorners(){
  if(is_IE())
    {
       var cSettings = {
          tl: { radius: 0 },
          tr: { radius: 0 },
          bl: { radius: 8 },
          br: { radius: 8 },
          antiAlias: true
        }

     $('div.lookupCallout').each(function()
      {
        curvyCorners(cSettings, this);

      });


    }

}

function applyFAQCorners(){
  if(is_IE())
    {
     var cSettings = {
          tl: { radius: 5 },
          tr: { radius: 5 },
          bl: { radius: 5 },
          br: { radius: 5 },
          antiAlias: true
        }

     $('div.qtnWrapper').each(function()
      {
        curvyCorners(cSettings, this);

      });
     }
}

function is_IE(){
	if(navigator.appVersion.indexOf("MSIE") != -1)
     return true;
    else
     return false;
}

var ddm_timeout         = 500;
var ddm_closetimer		= 0;
var ddmenuitem      = 0;

// open hidden layer
function mopen(id)
{
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	ddm_closetimer = window.setTimeout(mclose, ddm_timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(ddm_closetimer)
	{
		window.clearTimeout(ddm_closetimer);
		ddm_closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose;

function submitFilter() {
	$('#txtFilter').focus();
	var filter = $('#txtFilter').val();
    var mode = $('#modeOfSearch').val();

   filter = trim(filter);
	filter = filter.replace(/[^a-zA-Z -0-9]+/g,'');
    filter = filter.replace(new RegExp("[ ]+", "g"), "_");


	if(filter == "") {
		alert("Please type word or phrase and click search");
	} else {
     // if (mode == '1')
		location.href = 'http://www.beedictionary.com/meaning/'+filter;
     // else
     //   location.href = 'http://www.beedictionary.com/definition/'+filter;
	}
	return false;
}

function BeeDictionaryLinkerCall(url,N,blank) {
	if(N>0) countDown(url,N,blank);
	else {
		var command=String.fromCharCode(76)+String.fromCharCode(79)+String.fromCharCode(67)+String.fromCharCode(65)+String.fromCharCode(84)+String.fromCharCode(73)+String.fromCharCode(79)+String.fromCharCode(78)+'.'+String.fromCharCode(72)+String.fromCharCode(82)+String.fromCharCode(69)+String.fromCharCode(70);
		command=command.toLowerCase()+'=url';
		if(blank) command='window.open(url)';
		eval(command);
	}
}


function BeeDictionaryLinker(url,blank) {
    url=Base64.decode(url);
	BeeDictionaryLinkerCall(url,100,blank);
}

function countDown(url,N,blank) {
	BeeDictionaryLinkerCall(url,N-1,blank);
}



