/**
 * should be loaded after jquery
*/


function getUrl(url,onSuccess,ajax){
	if(typeof(onSuccess)!="function"){
		onSuccess=function(){void(0);}
	}
	var dataType=(ajax?"json":"html");
	$.ajax({
		"dataType":dataType,
		"url":url,
		"processData":false,
		"success":onSuccess
	});
}

function loginBox(){
	getUrl("/interface/html/login/",function(html,stat){
		$(html).dialog({
			bgiframe:true,autoOpen:true,modal:true,height:210,title:'Sign In',
			buttons: {
				'Sign In':function(){
					var err=0;
					var email=$("#loginform #email");
					var pass=$("#loginform #password");
					if(!email.val()){
						email.addClass("ui-state-error");
						err=1;
					}else{
						email.removeClass("ui-state-error");
					}
					if(!pass){
						pass.addClass("ui-state-error");
						err=1;
					}else{
						pass.removeClass("ui-state-error");
					}
					if(err){	
						return;
					}
					$("#loginform fieldset").hide("fast");
					$("#loginform #progress").html("Signing in...").show("fast");
					$.ajax({
						"url":"/interface/ajax/login/",
						"dataType":"html",
						"type":"POST",
						"data":{"email":email.val(),"password":pass.val()},
						"success":function(html,stat){
							if(html=="1"){
								$("#loginform #progress").html("Signed In!");
								location.reload();
							}else{
								$("#loginform #progress").html("Error signing in");
								$("#loginform fieldset").show("fast");
							}
						}
					})
					
					
					
				}
			}
		});
	})
}


function postReview(){
	getUrl("/interface/html/review/",function(html,stat){
		//preload autocomplete lib
		//if(!postReview.loaded){
			$.getScript("/assets/js/jquery.autocomplete.js",function(){
				$("#movie").autocomplete("/interface/ajax/movielist/",{timeout:400,minChars:3,validSelection:true,after:function(){
					$("ul.autocomplete").css({"top":"auto","left":"auto"});
				},parameters:{},ignorePosition:true,ignoreHilite:true});
				postReview.loaded=1;
			});
		//}else{
			
		//}
		//open dialog
		$(html).dialog({
			bgiframe:false,autoOpen:true,modal:true,height:290,title:'Post Your Movie Review',closeOnEscape:true,draggable:true,resizable:true,
			close:function(event,ui){$(this).html("")}
		}).append('<link rel="stylesheet" href="/assets/css/reviewbox.css" type="text/css" />');
		//character counter
		function validateRevVal(){
			var val=$("#status").val();
			$("#charlimit em").html(140-val.length);
			if(val.length>140){
				$("#status").val(val.substring(0,140));
				return false;
			}
			return true;
		}
		$("#status").keypress(validateRevVal).change(validateRevVal).keyup(validateRevVal).focus(validateRevVal).blur(validateRevVal).change(validateRevVal);
		//validation
		//submission
		
		
	});
	return false;
}


function insertTextToInput( input, insText ) {//---this will insert text into an input at the current curosr position
	input.focus();
	if( input.createTextRange ) {
		document.selection.createRange().text += insText;
	} else if( input.setSelectionRange ) {
		var len = input.selectionEnd;
		input.value = input.value.substr( 0, len )	+ insText + input.value.substr( len );
		input.setSelectionRange(len+insText.length,len+insText.length);
	} else { 
		input.value += insText; 
	}
}
/** 
 * limit number of chars in a textarea and display count of chars left
*/
function limitChars(textid, limit, infodiv){
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(!limit)limit=$("#"+textid).attr("maxlength");
	if(!limit)return true;
	if(textlength > limit){
		$('#'+infodiv).html("0");
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}else{
		$('#'+infodiv).html((limit-textlength));
		return true;
	}
}


function headerSearch(obj){
	$(obj).addClass("default");
	$(obj).val("");
	if(!headerSearch.reqsLoaded){
		$("head").append('<link rel="stylesheet" href="/assets/css/header-autocomplete.css" type="text/css" />');
		$.getScript("/assets/js/jquery.autocomplete.js",function(){
			$("#hq").autocomplete("/interface/ajax/movielist/",{timeout:400,minChars:3,validSelection:false,parameters:{},ignorePosition:true,ignoreHilite:true,allowenter:true,
				onclick:function(){
				$("#hq").parent("form").submit();
			}});
		});
	}
}

/**
 * post twitter reply with movie backlink
*/
function postReply(rawId,statusUser,backlink,replyStatusId){
	if(!rawId || !statusUser )
		return "";
	var url="/interface/html/twitreply/?raw_data_id="+rawId+"&link="+escape(backlink);
	
	getUrl(url,function(html,xx){
		$("head").append('<link rel="stylesheet" href="/assets/css/twitreply.css" type="text/css" />');
		$(html).dialog({
			bgiframe:true,autoOpen:true,modal:true,
			height:305,title:'Reply to: '+statusUser,closeOnEscape:true,
			close:function(){$(this).html("")},
			buttons:{
				"Submit":function(){
					var val="@"+statusUser+" "+$("#status").val()+" "+backlink;
					var url="http://twitter.com/home?status="+	escape(val)+"&in_reply_to_status_id="+replyStatusId+"&in_reply_to="+statusUser+"&source=tinymovi.es";
					window.open(url);
					$(this).dialog('close');
				}
			}//end buttons
		});//end dialog
		$("#status").keyup(function(){limitChars("status",$("#status").attr("maxlength"),"charcountbox");});
	});//end onload for geturl
}


function updateMovieChart(newTimeFrame,relLink){
	var src=$("#chart").attr("src");
	src=src.replace(/timeframe%3D(.*)/,'timeframe%3D'+newTimeFrame);
	$("#chart").attr("src",src);
	$.each($(relLink).parents("div").children("a"),function(i,val){
		$(val).removeClass();
	});
	$(relLink).addClass("on");
	
}


function ReadCookie (name) {
      var namearg = name + "=";
      var nlen = namearg.length;
      var clen = document.cookie.length;
      var i = 0;
      while (i < clen) {
        var j = i + nlen;
        if (document.cookie.substring(i, j) == namearg) {
           var endpos = document.cookie.indexOf (";", j);
           if (endpos == -1) endpos = document.cookie.length;
           return unescape(document.cookie.substring(j, endpos));
	  }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
      }
      return "";
    }


function WriteCookie(name, value,expireAtSession,domain) {
	var expstr="";
	var vals=new Array(name+"="+escape(value));
	if(!domain)domain="twitik.com";
	if(!expireAtSession){
		var expdate=new Date();
		// expire cookie in 10 years by default
		expdate.setTime(expdate.getTime()+10*365*24*60*60*1000);
		vals[vals.length]="expires="+expdate.toGMTString();
	}
	vals[vals.length]="path=/";
	vals[vals.length]="domain=."+domain;
	document.cookie=vals.join("; ");
}
function SetCookie(name,val){WriteCookie(name,val);}
function DeleteCookie (name,domain) {
  var expdate = new Date();
  if(!domain)domain="twitik.com";
  expdate.setTime (expdate.getTime() - 1);  // Already gone!
  var cval = ReadCookie (name);
  document.cookie = name + "=" + cval + "; expires=" + expdate.toGMTString()+"; path=/; domain=."+domain;
}



