/*
 *  Copyright 2009 TwinACT LLC (info@twinact.com). All Rights Reserved.
 *  Filename: headzzup.js
 *  Description: 
 */

var ta_imgdir = '../images/';
var ta_swfdir = '../media/';
var ta_cachedir = '../cache/';
//var ta_displayurl = 'http://darkstar/phpdev/headzzup/clips/clip.php?token=';
//var ta_mediapath = 'http://192.168.0.103/phpdev/headzzup/media/';
var ta_displayurl = 'http://www.headpuppets.com/cartoon/clips/clip.php?token=';
var ta_mediapath = 'http://www.headpuppets.com/cartoon/media/';

function Current(token, uid){
    this.token = token;
    this.uid = uid;
    this.tab = 0;
    this.profileid = 0;
    this.profilename = 0;
    this.tagid = 0;
    this.tagname = 0;
    this.title = '';
    this.message = 'Your message goes here.';
    this.actor = '7';
    this.back = '2';
    this.prop = '1';
    this.charpage = 1;
    this.backpage = 1;
    this.proppage = 1;
    this.keywords = '';
    this.lastuser = '';
}
var current = 0; //IE 7 broke when current was not set or set = 0;

function ta_$(id){ return document.getElementById(id); }
	
function ta_getMovie(movieName) {
    return (navigator.appName.indexOf ("Microsoft") != -1) ? document.getElementById(movieName) : document.embeds[movieName];
}

function pad(str, padchar, n){
    str = str + ""; // ensure string for Javascript
    return (str.length<n) ? pad(padchar+str, padchar, n) : str;
}

function ta_swap(type, data, page){
	ta_AgentObj = ta_getMovie('ta_Agent');
    switch (type){
		case 'char':
            current.actor = data;
            current.charpage = page;
            var temp = ta_$('cur_char');
            $("#cur_char").attr({ src: ta_imgdir+'char/char'+pad(data, '0', 3)+'.jpg' });
            ta_AgentObj.SetVariable("newActor", data);
            break;
		case 'back':
            current.back = data;
            current.backpage = page;
            $("#cur_back").attr({ src: ta_imgdir+'back/back'+pad(data, '0', 3)+'.jpg' });
            ta_AgentObj.SetVariable("newBackground", data);
            break;
		case 'prop':
            current.prop = data;
            current.proppage = page;
            $("#cur_prop").attr({ src: ta_imgdir+'prop/prop'+pad(data, '0', 3)+'.jpg' });
            ta_AgentObj.SetVariable("newProp", data);
            break;
        case 'message': 
            data = stripBR(stripESC(data));
            ta_AgentObj.SetVariable("newText", data);
            break;
        default: 
            break;
	}
    //$("#popgrid").hide();
}

function ta_text(){
    ta_AgentObj = ta_getMovie('ta_Agent');
    var title = document.getElementById('title').value;
    var mess = document.getElementById('message').value;
    if (mess == '') {
        ta_alert("Please enter a message to be spoken.");
        return;
    }
    $.post('clipserver.php',  { action: 'checkclipcontent', title: title, message: mess },  function(json){
        if (json > 0) {
            ta_alert("There appears to be something wrong with the title or message of this clip.");
        } else {
            if (title != null) ta_AgentObj.SetVariable("newTitle", title);
            ta_AgentObj.SetVariable("newText", mess);
            ta_AgentObj.SetVariable("newSpeak", mess);
        }
    }); 
}

function ta_speak(){
    ta_AgentObj = ta_getMovie('ta_Agent');
    ta_AgentObj.SetVariable("newSpeak", 1);
}

function ta_play(){
    ta_AgentObj = ta_getMovie('ta_Agent');
    ta_AgentObj.SetVariable("topballoon._visible", 0);
    ta_AgentObj.SetVariable("newSpeech", '../cache/'+current.token);
}

function ta_display(text){ 
    ta_AgentObj = ta_getMovie('ta_Agent');
	ta_AgentObj.SetVariable("newText", unescape(text));
}

/* Load a swf movie into the player (level 1) */
function ta_say(id){
    ta_AgentObj = ta_getMovie('ta_Agent');
    ta_AgentObj.SetVariable("newSpeech",id);
}

function ta_save(uid){
    var mess = $('#message').val();
    var title = $('#title').val();
    var privacy = $('input:radio[name=privacy]:checked').val();
    if (title == '') {
        ta_alert("Please enter a short title for this clip.");
        return;
    }
    if ((mess == '') || (mess == 'Your message goes here.')) {
        ta_alert("Please enter a message to be spoken.");
        return;
    }
    $.getJSON('clipserver.php?action=checkdailycount&uid='+uid, '', function(json){
        if (json > 10){
            ta_alert('We are sorry but we only allow you to create 10 clips per day. <div>Please return tomorrow if you want to create more clips.</div>');
        } else {
            $.post('clipserver.php',  { action: 'checkclipcontent', title: title, message: mess },  function(json){
                if (json > 0) {
                    ta_alert("There appears to be something wrong with the title or message of this clip.");
                } else {
                    $('#pubpanel').html('<img src="../images/working.gif" style="margin: 10px auto;">');
                    $.post('clipserver.php',  { action: 'saveclip', actor: current.actor, backdrop: current.back, prop: current.prop, title: title, message: mess, privacy: privacy },  function(json){
                        if (json) { window.location.href = 'clip.php?token='+json.token; }
                    }, "json");
                }
            });
        }
    });
}


/* Firefox likes this */
function ta_Agent_DoFSCommand (command, args){
         //alert("Unrecognized Flash Command: " + command);
}

function stripESC(str){
	return str.replace(/\t|\r|\n/gi,"");
} 

function stripCR(str){
	return str.replace(/\r/gi,"");
}

function stripBR(str){
	return str.replace(/<br>|<br \/>/gi,"\n");
}

function stringFilter (input) {
	filteredValues = "\r";
	var i;
	var returnString = "";
	for (var i = 0; i < input.length; i++) {
		var c = input.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

//var rated = 0; This would only work until page is refreshed
function showstar(n){
    //if (rated) return;
    for (var i=1;i<6;i++){
        document.getElementById('star_'+i).style.backgroundPosition = (i <= n) ? "left bottom" : "left top";
    }
}

function rateit(){
    if (current.uid){
        $.getJSON('clipserver.php?action=getrating&token='+current.token+'&uid='+current.uid, '' , function(json){
            if (json){
               $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" />You have already rated this clip.').show();
            } else {
                var content = '<div onmouseover="showstar(0);" id="ratinglabel">Rate this:</div>'
+'<a href="#" onclick="rate(1);" id="star_1" class="star" title="1 star out of 5" onmouseover="showstar(1);">&nbsp;</a>'
+'<a href="#" onclick="rate(2);" id="star_2" class="star" title="2 stars out of 5" onmouseover="showstar(2);">&nbsp;</a>'
+'<a href="#" onclick="rate(3);" id="star_3" class="star" title="3 stars out of 5" onmouseover="showstar(3);">&nbsp;</a>'
+'<a href="#" onclick="rate(4);" id="star_4" class="star" title="4 stars out of 5" onmouseover="showstar(4);">&nbsp;</a>'
+'<a href="#" onclick="rate(5);" id="star_5" class="star" title="5 stars out of 5" onmouseover="showstar(5);">&nbsp;</a>';
                 $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="ratingstars">'+content+'</div>').show();
            } 
        });
    } else {
         $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="alertmsg"><a href="signin.php">Sign In</a> to rate this clip.</div>').show();
    }
}

function rate(n){
    //if (rated) return;
    $.getJSON('clipserver.php?action=postrating&token='+current.token+'&uid='+current.uid+'&rating='+n, '' , function(json){
        //rated = 1;
        $('#ratingstars').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" />Thank you for your rating.');
        $('#ratingpanel').load('groupserver.php?data=ratingpanel&token='+current.token+'&uid='+current.uid);
    });
    return false;
}

function flag(){
    var temp = '<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" />'
    + '<div id="extramsg"><form><div>Please indicate why you are flagging this clip.</div>'
    + '<div><label><input type="radio" name="flagcode" value="1">Obscene or offensive language</label></div>'
    + '<div><label><input type="radio" name="flagcode" value="2">Derogatory comments/personal attack</label></div>'
    + '<div><label><input type="radio" name="flagcode" value="3">Spam or off-topic comment</label></div>'
    + '<div style="text-align: center;"><a href="#" style="margin: 0px auto; float: none;" class="newbutton" onclick="flagclip(); return false;">Submit</a></div>'
    + '</form></div>';
    $('#extrapanel').html(temp).show();
}

function flagclip(){
    var code = $('input:radio[name=flagcode]:checked').val();
    $.getJSON('clipserver.php?action=flagclip&token='+current.token+'&uid='+current.uid+'&flagcode='+code, '' , function(json){
        $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" />Thank you for flagging this clip. We have scheduled it for review.');
    });
}

function postcomment(){
    $.getJSON('clipserver.php?action=postcomment&token='+current.token+'&uid='+current.uid+'&comment='+escape($("#comment").val()), '' , function(json){
            showpage('comments', 1);
            //$("#xbox").corners();
    });
}

function flagcomment(commentid, page){
    $.getJSON('clipserver.php?action=flagcomment&commentid='+commentid+'&uid='+current.uid, '' , function(json){
        $('#comment_'+commentid).html('Thank you.');
    });
}

function deletecomment(commentid, page){
    $.getJSON('clipserver.php?action=deletecomment&commentid='+commentid+'&uid='+current.uid, '' , function(json){
            showpage('comments', page);
            //$("#xbox").corners();
    });
}

function deleteclip(token){
    $('#btn_'+token).html('<img src="../images/working.gif" style="margin-right: 15px;" border="0" />');
    $.getJSON('clipserver.php?action=deleteclip&token='+token+'&uid='+current.uid, '' , function(json){
            window.location.href = window.location.href;
    });
}

function subscribe(user, buttonid){
    if (current.uid){
        $.getJSON('clipserver.php?action=subscribe&user='+user+'&uid='+current.uid, '' , function(json){
            $('#'+buttonid).unbind('click');
            $('#'+buttonid).click(function () {
                unsubscribe(user, buttonid); return false;
            });
            $('#'+buttonid).html('Unsubscribe');
        });
    } else {
        window.location.href = 'signin.php'; //add a message?
    }
}

function unsubscribe(user, buttonid){
    if (current.uid){
        $.getJSON('clipserver.php?action=unsubscribe&user='+user+'&uid='+current.uid, '' , function(json){
            $('#'+buttonid).unbind('click');
            $('#'+buttonid).click(function () {
                subscribe(user, buttonid); return false;
            });
            $('#'+buttonid).html('Subscribe');
        });
    } else {
        window.location.href = 'signin.php'; //add a message?
    }
}

function addfavorite(token){
    if (current.uid){
        $.getJSON('clipserver.php?action=addfavorite&token='+token+'&uid='+current.uid, '' , function(json){
            $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="extramsg">The clip has been added to your favorites. <a href="#" onclick="removefavorite(\''+token+'\'); return false;">Remove It</a></div>').show();
        });
     } else {
         $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="alertmsg"><a href="signin.php">Sign In</a> to access your favorites.</div>').show();
    }
}

function removefavorite(token){
    if (current.uid){
        $.getJSON('clipserver.php?action=removefavorite&token='+token+'&uid='+current.uid, '' , function(json){
            $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="extramsg">The clip has been removed from your favorites. <a href="#" onclick="addfavorite(\''+token+'\'); return false;">Add It</a></div>').show();
        });
     } else {
        $('#extrapanel').html('<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" /><div id="alertmsg"><a href="signin.php">Sign In</a> to access your favorites.</div>').show();
    }
}

/* for favorites page */
function removefav(token){
    $('#btn_'+token).html('<img src="../images/working.gif" style="margin-right: 15px;" border="0" />');
    $.getJSON('clipserver.php?action=removefavorite&token='+token+'&uid='+current.uid, '' , function(json){
            window.location.href = window.location.href;
    });
}

function checkusername(){
    var username = $('#username').val().trim();
    var match = /^[a-zA-Z0-9_]+$/.test(username);
    if (!match) {
        $('#usernamefeedback').html('<label>&nbsp;</label>A username may contain only numbers and letters and _.');
        return;
    }
    //check for space, tab gt lt? @
    if ((username.length < 3) || (username.length > 16)) {
        $('#usernamefeedback').html('<label>&nbsp;</label>A username must be 3 to 16 characters in length.');
        return;
    }
    $.getJSON('clipserver.php?action=checkusername&username='+username, '' , function(json){
        if (json) {
            $('#usernamefeedback').html('<label>&nbsp;</label>Unavailable. Please try another name.');
        } else {
            $('#usernamefeedback').html('<label>&nbsp;</label>Available.');
        }
    });
}

function toggleshare(token, title){
    if (document.getElementById('share') == null) return;
    var url = ta_displayurl+token;
    var escurl = escape(url);
    var esctitle = escape(title);
    var embedraw = '<object width="400" height="250"><param name="movie" value="'+ta_mediapath+'index.php?token='+token+'"></param><param name="base" value="'+ta_mediapath+'"><param name="allowScriptAccess" value="always"></param><embed src="'+ta_mediapath+'headclip.swf?token='+token+'" type="application/x-shockwave-flash" base="'+ta_mediapath+'" allowScriptAccess="always" width="400" height="250"></embed></object>';
    var embed = embedraw.replace(/\"/g, '&quot;');
    var content = '<input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#extrapanel\').hide();" />'
    +'<div id="shares">'
    +'<form style="display: inline;" id="myspacepostto" method="post" action="http://www.myspace.com/index.cfm?fuseaction=postto" target="_blank">'
    +'<input type="hidden" name="t" value="MySpace Post To Feature Example" />'
    +'<input type="hidden" name="c" value="'+embed+'" />'
    +'<input type="hidden" name="u" value="http://www.myspace.com" />'
    +'<input type="hidden" name="l" value="3" />'
    +'<a id="myspace" class="share" style="margin-left: 0px;" href="document.status=\'Post to MySpace\'" onclick="document.getElementById(\'myspacepostto\').submit();return false;">MySpace!</a>'
    +'</form>'
    +'<a id="facebook" class="share" href="http://www.facebook.com/sharer.php?u='+escurl+'">Facebook</a>'
    +'<a id="twitter" class="share" href="http://twitter.com/home?status=Check%20this%20out%20--%20'+esctitle+'%20'+escurl+'">Twitter</a>'
    +'<a id="digg" class="share" href="http://digg.com/submit?phase=2&amp;url='+escurl+'&amp;title='+esctitle+'&amp;topic=entertainment">Digg</a>'
    +'<a id="delicious" class="share" href="http://del.icio.us/post?title='+esctitle+'&amp;url='+escurl+'">Del.icio.us</a>'
    +'<a id="stumbleupon" class="share" href="http://www.stumbleupon.com/submit?title='+esctitle+'&amp;url='+escurl+'">StumbleUpon</a>'
    +'</div>';
    $('#extrapanel').html(content).show();
}

 
function ta_feedback(){
    if ($('#feedbox').length == 0) {
        var obj = '<div id="feedbox" class="jqmWindow"><div style="padding:10px;">'
        + '<h3>Send Feedback</h3><input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#feedbox\').jqmHide();" />'
        + '<textarea id="feedback"></textarea>'
        + '<div><label for="email">E-mail address (optional):</label><input type="text" id="email" value="" /></div>'
        + '<div style="margin-top: 10px;"><a href="#" style="margin-left: 130px;" class="newbutton" onclick="$(\'#feedbox\').jqmHide(); return false;">Cancel</a> <a href="#" style="margin-left: 5px;" class="newbutton" onclick="sendfeedback(); return false;">Submit</a></div>'
        + '<div style="clear:both;"></div>'
        + '</div></div>';
        $('#sitebg').append(obj);
        $('#feedbox').corners();
        $('#feedbox').jqm({modal: true});
    }
    $('#feedbox').jqmShow();
    //$('#feedbox').modal({ minWidth:400, minHeight:250, overlayCss: { backgroundImage: 'url(../images/gridbg.gif)' } });
}

function sendfeedback(){
    var feedback = $('#feedback').val();
    var email = $('#email').val();
    $.getJSON('clipserver.php?action=postfeedback&feedback='+escape(feedback)+'&email='+email, '' , function(json){
	$('#feedbox').html('<div class="center" style="padding: 10px 0px 0px 10px;"><h3>Thank you for your feedback.</h3><input class="closebox" type="image" src="../images/closex.gif" onclick="closefeedbox(); return false;" /></div>'); 
    });
}

// Created because of parsing problems with above expression
function closefeedbox(){
    $('#feedbox').jqmHide();
}

function charactercount(field, target, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    } else {
        document.getElementById(target).innerHTML = maxlimit - field.value.length;
    }
    if (field.id == 'title') current.title = field.value;
    if (field.id == 'message') current.message = field.value;
}

function showstatus(msg){
    window.status = msg;
    return true;
}

function ta_swf(token, mode){
    var swf = ta_swfdir+'headclip.swf?token='+token+'&playmode='+mode;
    var content = '<object id="ta_Agent" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="400" height="250">'+
	'<param name="movie" value="'+swf+'" />'+
	'<param name="base" value="." />'+
	'<param name="quality" value="high" />'+
	'<param name="wmode" value="opaque" />'+
	'<param name="bgcolor" value="#c3c8d1" />'+"\n"+
	'<embed name="ta_Agent" src="'+swf+'" base="." quality="high" wmode="opaque" bgcolor="#c3c8d1"  width="400" height="250" type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer"></embed></object>';
    return content;
}

function ta_swfsize(token, mode, w, h){
    var swf = ta_swfdir+'headclip.swf?token='+token+'&playmode='+mode;
    var content = '<object id="ta_Agent" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+w+'" height="'+h+'">'+
	'<param name="movie" value="'+swf+'" />'+
	'<param name="base" value="." />'+
	'<param name="quality" value="high" />'+
	'<param name="wmode" value="opaque" />'+
	'<param name="bgcolor" value="#c3c8d1" />'+"\n"+
	'<embed name="ta_Agent" src="'+swf+'" base="." quality="high" wmode="opaque" bgcolor="#c3c8d1"  width="'+w+'" height="'+h+'" type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer"></embed></object>';
    return content;
}

function ta_swfgallery(token, character, design, prop){
    var swf = ta_swfdir+'headclipmini.swf?token='+token+'&actor='+character+'&back='+design;
    if (prop) swf = swf+'&prop='+prop;
    var content = '<object id="ta_Agentx" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="110" height="69">'+
	'<param name="movie" value="'+swf+'" />'+
	'<param name="base" value="." />'+
	'<param name="quality" value="high" />'+
	'<param name="wmode" value="opaque" />'+
	'<param name="bgcolor" value="#c3c8d1" />'+"\n"+
	'<embed name="ta_Agentx" src="'+swf+'" base="." quality="high" wmode="opaque" bgcolor="#c3c8d1"  width="110" height="69" type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer"></embed></object>';
	return content;
}

function popgrid(data, page){
    $(".minitabon").removeClass('minitabon');
    $("#"+data+"tab").addClass('minitabon');
    $("#menu").load("groupserver.php?data="+data+"&page="+page, '', function(){
        //$("#menu").show();
    });
}

function showpage(data, page){
    switch (data) {
        case 'search.php':
            $("#related").load("groupserver.php?data="+data+"&page="+page+"&keywords="+current.keywords);
            break;
        case 'profile.php':
            $("#related").load("groupserver.php?data="+data+"&page="+page+"&user="+current.user);
            break;
        case 'comments':
            $("#commentpanel").load("groupserver.php?data="+data+"&page="+page+"&token="+current.token);
            break;
        default:
            $("#related").load("groupserver.php?data="+data+"&page="+page);
            break;
    }
}

function ta_alert(message){
    if ($('#alertpanel').length == 0) {
        var obj = '<div id="alertpanel" style="width: 293px;" ><input class="closebox" type="image" src="../images/closex.gif" onclick="$(\'#alertpanel\').hide();" /><div id="alertmsg"></div></div>';
            $('#inset').prepend(obj);
    }
    $('#alertmsg').html(message);
    $('#alertpanel').corners();
    $('#alertpanel').show();
}

// onkeypress="return submitonenter(this,event)"
function submitonenter(myfield,e){
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13){
        myfield.form.submit();
        return false;
    } else {
        return true;
    }
}