/*******************************************
 *
 * Naughty API - by Naughty America
 * Dependencies: jQuery
 *
 *******************************************/

function debug_print(message, custom_div) {
    if(!custom_div) {
        custom_div = '#debug_message';
    }
    $(custom_div).fadeOut('fast').text(message).fadeIn('fast');
    if(window.console) {
        console.log(message);
    }
}

if(!OA_show) {
	
	var OA_show = function() {};
}

// Device detection
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isPS3 = navigator.userAgent.match(/Playstation 3/i) != null;
var isIE6 = navigator.userAgent.match(/MSIE 6.0/i) != null;
//var is64bitWindows = ((navigator.userAgent.match(/WOW64/i) != null) || (navigator.userAgent.match(/Win64/i) != null));

/**** OpenX: Single Page Call ****/
//Name the OpenX ad zones for readability
var OA_zones = {
    'na-tour-slide-down' : 65,
    'na-tour-footer' : 60,
    'na-members-sidebar': 34,
    'na-members-footer': 1,
    'na-members-ppm': 71,
    'na-walled-garden-footer': 83,
    'na-test-flash': 95,
    'na-blue-area': 116,
    'brandreach-footer': 130,
    'na-members-landing': 140,
    'na-members-postLogin': 141,

    'na-mobile-ma-header': 18,
    'na-mobile-ma-footer': 17,
    
    '703-members-footer': 45,
    '703-members-sidebar': 46,
    '703-tour-slide-down' : 69,
    '703-tour-footer' : 63

};

// Track an event with Google Analytics (Async style)
var click_event_number = 1;
function track_event(category, action, opt_label, opt_value) {

	if(window._gaq != undefined) {
		console.log('Tracking event: ' + category + ' / ' + action + ' / ' + opt_label + ' : ' + click_event_number);
		_gaq.push(['_trackEvent', category, action, opt_label, click_event_number]);
		click_event_number++;
	}
}
// A catch-all function to tell various places on the site whether or not the browser can display flash
function non_flash_browser() {

	return (isiPad || isPS3);
}

/********* Lazy loading functions ***********/

function load_delayed_images(id, attr) {
    if(attr == undefined) {
        attr = 'original';
    }
    $('#' + id + ' img[delay_src]').each(function() {
        $(this).attr(attr, $(this).attr('delay_src'));
    });
}

// If images had a temporary attribute so that they could delay their loading, force them to appear
function force_image_loading(id, temp_attr) {
    if(temp_attr == undefined) {
    	temp_attr = 'original';
    }
    
    $('#' + id + ' img[' + temp_attr + ']').each(function() {
        $(this).attr('src', $(this).attr(temp_attr));
    });
    console.log('NOTE: All images with the "'+ temp_attr + '" attribute have been forced to load.');
}

// Lazy load all images that were prepped by having their src tags moved to "original"
function queue_delayed_images() {

    $("img[original]").lazyload({
        effect: "fadeIn",
        failurelimit: 400,
        threshold: 300
    });
}

/********* /Lazy loading functions ***********/

// Google Website Optimizer Conversion Script
function join_button_tracking() {

    try {
        var gwoTracker=_gat._getTracker("UA-10369514-2");
        gwoTracker._trackPageview("/2051691784/goal");
        console.log("Successfully tracked a join button click.");
    }
    catch(err)
    {
        console.log("Error involving Join button tracking: " + err);
    }
}

function post_comment(body, topic_id) {

}

/**
 * Report a deprecated function to the email specified
 */
function deprecated_function_report(email) {
    if(!email) {
        email = 'daryl@latouraineinc.com';
    }

    // Email alert
    naughty_rpc('deprecated_function_report', { message: arguments.callee.caller.toString() + ' called from: ' + location.href, email: email }, function() {});
}

/**
 * Place an actor's picture in the given HTML element (jQuery selected)
 * Usage: change_actor_picture('.spouse_picture', 1);
 */
function change_actor_picture(element, a_id, brand) {
    $(element).attr("src","http://data." + brand + ".com/upload/source/actors/" + a_id + "/" + a_id + "vert.jpg");
}


function set_user_info(accountid, property, value, is_popup) {
    debug_print('Setting user info for (' + accountid + '): ' + property + ' = ' + value);
    naughty_rpc('set_user_info', { accountid: accountid, property: property, value: value }, function(data) {
        debug_print('Set user info: done.');
        if(is_popup) {
            destroy_popup();
        }
    });
}

/**
 * Calls the NaughtyCMS method with the parameters in the params array (e.g. BedroomsUser.checkDisplayName,
 */
function naughty_rpc(method, params, callback) {
    var sub_directory = '/';
    var this_domain = document.domain;
    var index_file = 'index.php';
    var serialized_params = serialize(params);
    
    // Special provisions for api.naughtyamerica.com & www.naughtyamerica.com
    if(this_domain.search("api.naughtyamerica.com") >= 0) {
        sub_directory = '/labs/';
    }
    // Custom subdirectory for localhost testing
    else if(window.poll_prefix != undefined) {
        sub_directory = '/' + window.poll_prefix;
    }

    if(this_domain.search("www.naughtyamerica.com") != -1 || this_domain.search("www.suite703.com") != -1) {
        index_file = 'index3.php';
    }

    // If the request is coming from another site (e.g., tools.naughtyamerica.com) target the tour instead
    if(params.offsite != undefined) {
    		sub_directory = 'http://tour.naughtyamerica.com' + sub_directory;
    }
    
    var url = sub_directory + index_file + "?m=misc&s=naughty-rpc&method=" + method;
    console.log('Naughty RPC: ' + url);
    $.post(url, { method: method, params: serialized_params}, function(data) { callback(data); }, "json");
}

/**
 * Save a setting
 */
function saveSetting(setting_name, setting_value,expiredays) {
    if(!expiredays) {
        expiredays = 1;
    }
    setCookie(setting_name, setting_value, expiredays);
}

function getCookie(c_name) {
    if (document.cookie.length>0)  {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) {
                c_end=document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

/**
 * Retrieve a setting
 */
function getSetting(setting_name) {
    return getCookie(setting_name);
}


/**
 * Sets a cookie to expire in the desired amount of days.
 */
function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+'; path=/';
}


/**
 * Load the desired template into the desired div id
 */
function load_template(element_id_or_class, template) {
    if(template) {
        $.get("/index.php?m=misc&s=loader", { template: template }, function(page) { $(element_id_or_class).html(page); });
    }
}

function login_response(data) {
    $('#bedroom_signup').val('Login!');
    if(data['response'] == 'error') {
        $('#message').addClass('bad_message').html(data['message'] + '<p/>');
    }
    else if(data['response'] == 'success') {
        $('#message').removeClass('bad_message').addClass('good_message').html('Success! You are now logged in.<p/>');
        $('#login_credentials').slideUp('fast');
        $('#bedroom_signup').fadeOut('fast');
        $('#bedroom_quit').val('Close Window');
    }
    else if(data['response'] == 'redirect') {
        top.location.href = data['url'];
    }
}

function popup_login(email, password) {
    $('#bedroom_signup').val('Processing...');
    naughty_rpc('AccountApi.checkPopupLogin', { username: email, password: password }, login_response);
}


/**
 * Show a web 2.0 style popup
 * var options = {}
 * options.args = { accountid: '2622', action: 'report' };
 * Usage (to load "report_user.tpl"): href="javascript:overlay_popup('report_user', options)"
 */
function overlay_popup(type, options, callback) {

    var sub_directory = '/', index_file = 'index.php';
    var this_domain = document.domain;
    if(window.poll_prefix != undefined) {
        sub_directory = '/' + window.poll_prefix;
    }

    console.log('Showing overleyed popup: ' + type);
    var arg_string = '';
    if(type == null) {
        type = 'bedroom_login';
    }

    // This will handle the placement
    if(!options) {
        options = { element: 'body' };
    }

    // Default height & width
    if(!options.width) { options.width = 300 }
    if(!options.height) { options.height = 300 }

    var arg_string = '';
    if(options.args) {
        for(var i in options.args) {
            arg_string += '&' + i + '=' + options.args[i];
        }
    }
    // Add the background graphic
    $('body').append('<div id="overlay_mask"></div>');

    // Add the overlay element
    //$(options.element).add('<div id="overlay_popup"></div>');
    $('body').append('<div id="overlay_popup_container"><div id="overlay_popup"></div></div>');

    if(this_domain.search("www.naughtyamerica.com") != -1 || this_domain.search("www.suite703.com") != -1) {
        //index_file = 'index3.php';
    }

    switch(type) {
        case 'bedroom_login':
            $('#overlay_popup').hide().css('height', options.height).css('width', options.width).load('/index.php?m=misc&s=loader&template=popup_login', {}, function(data) { $(this).slideDown('slow'); });
            $('#overlay_mask').animate({ opacity: .7 }, 'slow');
            break;
        default:
            var url = target_domain + sub_directory + index_file + '?m=misc&s=loader&template=' + type + arg_string;
            if (options.url != null) {
                url = options.url;
            };
            $('#overlay_popup').hide()
                               .css('height', options.height)
                               .css('width', options.width)
                               .load(url, {}, function(data) {
                                    $('#overlay_mask').animate({ opacity: .7 }, 'slow');
                                    $(this).slideDown('slow');
                                });
            break;
    }
}

// Destroy the overlayed popup
// @param boolean no_reload Whether or not to refresh the page
// Usage: destroy_popup(true);  // This will destroy the popup without reloading the page
function destroy_popup(no_reload) {

    console.log('Destroying overleyed popup');
    $('#overlay_popup').slideUp('slow').html('').remove();
    $('#overlay_mask').animate({ opacity: 0 }, 'fast').remove();
    //top.location.reload(true);
    if(no_reload == undefined) {
        top.location.href = top.location.href;
    }
}

function ajaxFileUpload(account_id)
{
    //starting setting some animation when the ajax starts and completes
    $("#loading")
    .ajaxStart(function(){
        $(this).show();
    })
    .ajaxComplete(function(){
        $(this).hide();
    });

    /*
    prepareing ajax file upload
    url: the url of script file handling the uploaded files
                fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
    dataType: it support json, xml
    secureuri:use secure protocol
    success: call back function when the ajax complete
    error: callback function when the ajax failed

        */
    $jQuery.ajaxFileUpload
    (
        {
            url: '/uploaders/doajaxfileupload.php',
            secureuri: false,
            fileElementId: 'fileToUpload_' + account_id,
            dataType: 'json',
            id: 5,
            success: function (data, status)
            {
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        console.log("Error: " + data.error);
                    }else
                    {
                        console.log("MSG: " + data.msg);
						alert(data.msg);
						destroy_popup();
                    }
                }
            },
            error: function (data, status, e)
            {
                console.log("AJAX Error: " + e);
            }
        }
    )

    return false;

}

function utf8_encode ( argString ) {
    // Encodes an ISO-8859-1 string to UTF-8
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/utf8_encode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)
    //
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {
                    continue;
                }

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function addslashes(str) {
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\0/g,'\\0');
    return str;
}

function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\0/g,'\0');
    str=str.replace(/\\\\/g,'\\');
    return str;
}

/*
 * Usage:
 *  retweet('RT @naughtyamerica {$topic.title}', '{$smarty.server.REQUEST_URI}');
 */
function retweet(message, url) {

    BitlyCB.shortenResponse = function(data) {
            var s = '';
            var first_result;
            var shortened_url = '';
            // Results are keyed by longUrl, so we need to grab the first one.
            for     (var r in data.results) {
                    first_result = data.results[r]; break;
            }
            for (var key in first_result) {
                    s += key + ":" + first_result[key].toString() + "\n";
                    if(key == 'shortUrl') {
                      shortened_url = first_result[key].toString();
                    }
            }
            // Twitter post URL: http://twitter.com/home/?status=
            var twitter_window = window.open('http://twitter.com/home/?status=' + message + ' ' + shortened_url);
            if (twitter_window == null || typeof(twitter_window)=="undefined") {
		alert('Be sure your popup blocker is not on!');
            }
    }
    BitlyClient.shorten(url, 'BitlyCB.shortenResponse');
}

function scroll_element(element_id_or_class, amount, direction) {

    console.log("Scrolling element: " + element_id_or_class + " " + direction + " by " + amount + "px")
    if(direction == 'right') {
        $(element_id_or_class).animate({scrollLeft: '+=' + amount + 'px'}, 1000, 'swing');
    }
    else if(direction == 'down') {
        $(element_id_or_class).animate({scrollTop: '+=' + amount + 'px'}, 1000, 'swing');
    }
    else if(direction == 'up') {
        $(element_id_or_class).animate({scrollTop: '-=' + amount + 'px'}, 1000, 'swing');
    }
    else {
        $(element_id_or_class).animate({scrollLeft: '-=' + amount + 'px'}, 1000, 'swing');
    }
}

function auto_slide_element(element_id_or_class, picture_size, num_pics_to_scroll, how_often_in_sec) {

    var container_width = $(element_id_or_class + ' .container').width();
    if($(element_id_or_class).scrollLeft() >= container_width - $(element_id_or_class).width()) {
        setTimeout(function() { scroll_element(element_id_or_class, container_width, 'left'); auto_slide_element(element_id_or_class, picture_size, num_pics_to_scroll, how_often_in_sec); }, how_often_in_sec * 1000);
    }
    else {
        setTimeout(function() { scroll_element(element_id_or_class, picture_size*num_pics_to_scroll, 'right'); auto_slide_element(element_id_or_class, picture_size, num_pics_to_scroll, how_often_in_sec); }, how_often_in_sec * 1000);
    }
}

function urlencode(url) {
    // URL Encode first!
    url = url.replace('&', '%26');
    url = url.replace('?', '%3F');
    url = url.replace(':', '%3A');
    url = url.replace(/\//g, '%2F');
    url = url.replace('=', '%3D');
    return url;
}

/****** AJAX file uploader *********/

jQuery.extend({


    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;

            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}
        var requestDone = false;
        // Create the request object
        var xml = {}
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{
			var io = document.getElementById(frameId);
            try
			{
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout")
			{
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try
										{
											$(io).remove();
											$(form).remove();

										} catch(e)
										{
											jQuery.handleError(s, xml, null, e);
										}

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 )
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';
            }
            else
			{
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();

        } catch(e)
		{
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return {abort: function () {}};

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})

/***************
 * Ratings API *
 ***************/
/*
 * Usage:
 *   rate_scene(2356, 24, 5);
 */

var ratings_module = '/index.php?m=api&s=ratings';

/*
 * entry_id: of the article, comment, or scene
 * member_id: of the person rating
 * rating: 1-5
 */
function rate_scene(entry_id, member_id, rating) {
    rate_entry('scene', entry_id, member_id, false, rating);
}

function rate_comment(entry_id, member_id, rating) {
    rate_entry('comment', entry_id, member_id, false, rating);
}

function rate_show(entry_id, member_id, channel, rating) {
   rate_entry('show', entry_id, member_id, channel, rating);
}

function record_vote(type, entry_id, rating) {
  var mydate = new Date;
  var one_day = 60*60*24*1000;dislikes_this_topic

  mydate.setTime(mydate.toGMTString()+one_day+one_day);
  cookie_val = type + '_' + entry_id + '=' + rating + '; expires='+mydate.toGMTString()+'; path=/';
  document.cookie = cookie_val;
}

function already_voted(type, entry_id, member_id) {

  return (get_cookie(type + "_" + entry_id));
}

function get_cookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }
  // a cookie with the requested name does not exist
  return null;
}

function rate_entry(type, entry_id, member_id, channel, rating) {

    var stats;
    if(!already_voted(type, entry_id, member_id)) {
        var query = ratings_module + "&action=save&entry_id=" + entry_id + "&type=" + type + "&rating=" + rating + "&member_id=" + member_id + "&channel=" + channel;
        $.getJSON( query,
            {
              m: 'api',
              s: 'ratings',
              entry_id: entry_id,
              type: type,
              rating: rating,
              member_id: member_id,
              channel: channel },
          function(data) {
            stats = data;
            //alert(data['stars_5'] + ' / ' + data['total_votes']);
            if(data) {
                $('.likes').html(data['like_percentage']);
                $('.votes').html(data['total_votes']);
            }
          });
          record_vote(type, entry_id, rating);
    }
    else {
        alert('You have already voted.');
    }
}

/* Parameters
 *  entry_id: Number representing the scene, show or comment
 *  type: 'scene', 'show', 'comment'
 *  stat: 'likes', 'dislikes', 'votes', 'average'
 */
function lookup_entry_rating(type, entry_id, stat, element) {
    $.get(ratings_module,
        { entry_id: entry_id,
          type: type,
          statistic: stat},
        function(data) {
            //alert(stat + ": " + data);

            return data;
    });
}

/* ********** Helper functions to make usage easier ********** */
function rate_data(entry_id, member_id, rating, rating_type, entry_date, brand) {
    rate_entry('ratings', entry_id, member_id, rating, rating_type, entry_date, brand);
}

function update_stats(increment_likes){
	var total = $(".total").html();
    var likes = $(".likes").val();

    // Add 1 to the total and update the page
    total = eval(total) + 1;
    $(".total").html(total);

    // Only increment the likes when someone hits a thumbs up
    if (increment_likes == true) {
        likes++;
    }

	var percent_val = Math.round(eval(likes) / eval(total) * 100);
	$(".percent").html(percent_val);
}

// AUTO UPDATE AGVERAGE RATING ON PAGE
function update_stars(rating, brand){
    var total = $(".total").html();
    var total_plus = eval(total)+1;
    if(total_plus == 0){
        total_plus = 1;
        $(".total").html(eval(total)-1);
    }else{
        $(".total").html(total);
    }
    var get_sum = $(".pre_sum").html();
    var sum = eval(get_sum) + eval(rating);
    var ave = Math.round(eval(sum) / eval(total_plus));
}

// GRAPHIC INTERFACE FOR RATING (BOX HOVER STATE)
function roll_box(id, box, brand)
    {
        var imgPath = new String();
        imgPath = document.getElementById(id).style.backgroundImage;

        if(box == box)
        {
            document.getElementById(id).style.backgroundImage = "url(http://content.naughtyamerica.com/naughty/public/images/"+ brand +"/stars/active_box.png)";
        }
        if(box == 0)
        {
            document.getElementById(id).style.backgroundImage = "url(http://content.naughtyamerica.com/naughty/public/images/"+ brand +"/stars/inactive_box.png)";
        }
    }

// Swaps out boxes and posts members rating
function update_box(id, rating, actor_name)
	{
		$(".update"+id).hide('slow');
		$(".update"+id).show('slow').html('You gave '+actor_name+' a rating of '+rating);
	}

function ratings_update(id, rating, type){

	if(type == 'scene')
	{
		// Update Total Votes
		var votes = $(".votes").html();
		var votes_plus = eval(votes)+1;
			if(votes_plus == 0){
				votes_plus = 1;
				$(".votes").html(eval(votes)-1);
			}else{
				$(".votes").html(votes_plus);
			}
		// Update Scene Average
		var get_sum = $(".sum").html();
		var sum = eval(get_sum) + eval(rating);
		var ave = (eval(sum) / eval(votes_plus)).toFixed(1);
		$(".average"+id).html(ave);
	}

	// Update Actors Averages
	var actor_votes = $(".actor_total"+id).html();
	var actor_votes_plus = eval(actor_votes)+1;

	if(actor_votes_plus == 0)
	{
		actor_votes_plus = 1;
	}

	var get_actor_sum = $(".actor_sum"+id).html();
	var actor_sum = eval(get_actor_sum) + eval(rating);
	var ave_actor = (eval(actor_sum) / eval(actor_votes_plus)).toFixed(1);

	$(".actor"+id).html(ave_actor);

}



function member_rating(entry_id, member_id, rating, rating_type, brand, ip, a_id){
    naughty_rpc('Ratings.save_rating', {entry_id: entry_id, member_id: member_id, rating: rating, rating_type: rating_type, brand: brand, ip: ip, a_id: a_id},
    function(data) {

        if(data != 'You have already voted.') {

            if(rating > 1) {
                // This means they pushed thumbs up
                update_stats(true);
            }
            else {
                // This means they pushed thumbs down
                update_stats(false);
            }  
        }
        else {
            console.log("The user HAS voted, this vote will be ignored: " + rating);
            // Let them know they have already voted
            alert(data);
        }

        
    });
}

function likes_this_topic(entry_id, member_id) {
    rate_entry('topic', entry_id, member_id, '', '5');
}

function dislikes_this_topic(entry_id, member_id) {
    rate_entry('topic', entry_id, member_id, '', '1');
}

function in_array (needle, haystack, argStrict)
{
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if ( (strict && haystack[key] === needle) || ( !strict && strict && haystack[key] == needle ) ) {
                return true;
            }
        }
    }

    return false;
}

