/// <reference path="jquery-1.3.2-vsdoc.js" />
var codeid;

$(document).ready(function() {
    speed = 30000;

    var coupon = 0;
    var bool = 0;
    var bool2 = 0;
    var feed = 0;

    $("html").click(function() {
        if ((coupon == 0) && (bool == 0)) $(".coupon").hide();
        if (bool == 1) bool = 0;
        if ((feed == 0) && (bool2 == 0)) $(".add_feed").hide();
        if (bool2 == 1) bool2 = 0;
    });

    $(".coupon").hover(function() {
        coupon = 1;
    }, function() {
        coupon = 0;
    });

    $(".add_feed").hover(function() {
        feed = 1;
    }, function() {
        feed = 0;
    });

    //$("#featured").paidTicker();			


    $(".add span").click(function() {
        bool2 = 1;
        if ($(this).next(".add_feed").is(":visible")) $(this).find(".add_feed").hide();
        else $(this).next(".add_feed").css('z-index', '10000').show();
    });

    $(".add span").hover(function() {
        $(this).css({ backgroundPosition: "0 100px" });
    }, function() {
        $(this).css({ backgroundPosition: "left bottom" });
    });

    $(".flaglink").click(function() {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: {},
            url: '/Code/Flag/' + $(this).attr("rel")
        });
        var flagId = $(this).attr("rel");
        $('#feeditem-' + flagId.slice(0, flagId.length - 2)).slideUp(700);
    });


    $(".retweetlink").click(function() {
        var cidClicked = $(this).attr("rel");
        $(this).replaceWith("<span style='font-size:10px;' id='rts" + cidClicked + "'>Sending...</span>");
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: {},
            url: '/Code/Retweet/' + $(this).attr("rel"),
            success: function(result) {
                //update message
                if (result.Success) {
                    //Tweet Successful
                    $('#rts' + result.Cid).replaceWith("Tweeted");
                    if (!result.Duplicate) {
                        var tweets = $('#rtc' + result.Cid).text();
                        var tweetcount = parseInt(tweets) + 1;
                        $('#rtc' + result.Cid).text(tweetcount);
                        CodeStatusUpdate(result.Cid, "Thanks!  You've Tweeted, and your Vote was Added!");
                    }
                    else {
                        CodeStatusUpdate(result.Cid, "Thanks.  You've Tweeted, but your Vote was not counted.");
                    }
                }
                else {
                    //Tweet Did not work
                    //$('#rtl' + result.Cid).html("Retweet");
                    CodeStatusUpdate(result.Cid, "Error: " + result.Message);
                    //update message
                    //$('#message').text('Status updated!').addClass('success').fadeIn('medium');

                }
            }

        });
    });

    $(".catalog span").hover(function() {
        $(this).css({ textDecoration: "none" });
    }, function() {
        $(this).css({ textDecoration: "underline" });
    });

});

function CodeStatusUpdate(tid, message) {
    $('#status' + tid).html(message);
    setTimeout('$("#status' + tid + '").slideUp(1000)', 3000);
}

$(function() {

    var website = $("#website"),
			ccode = $("#ccode"),
			description = $("#description"),
			expiredate = $("#expiredate"),
			allFields = $([]).add(website).add(ccode).add(description).add(expiredate),
			tips = $("#validateTips");

    function updateTips(t) {
        tips.text(t).effect("highlight", {}, 1000);
    }

    function checkLength(o, n, min, max) {

        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }

    }

    function checkRegexp(o, regexp, n) {

        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }

    $("#dialog").dialog({
        bgiframe: false,
        autoOpen: false,
        height: 480,
        width: 400,
        modal: true,
        buttons: {
            'Submit Code': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');

                bValid = bValid && checkLength(website, "website", 3, 65);
                bValid = bValid && checkLength(ccode, "ccode", 3, 50);
                bValid = bValid && checkLength(description, "description", 6, 140 - website.val().length - ccode.val().length - 10);

                //bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
                //bValid = bValid && checkRegexp(code,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
                bValid = bValid && checkRegexp(website, /^([0-9a-zA-Z\.\-])+$/, "Please enter a valid Website Domain Name (don't include http:// or www)");

                if (bValid) {
                    //logic here
                    $.post("/Code/Tweet/",
                        $("#codeform").serialize(),
                        function(data) {
                            if (data != "") {
                                if (data.indexOf("http") == 0) {
                                    window.location = data;
                                }
                                else {
                                    //alert(data);
                                    $('#updateStatus').addClass('ui-state-highlight');
                                    $('#updateStatus').text(data);
                                }
                            }
                        },
                        "text"
                        );
                    //$('#updateStatus').addClass('ui-state-highlight');
                    //$('#updateStatus').text('Tweeted this code!  Thanks for your submission');
                    $(this).dialog('close');
                }
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            $('#expiredate').datepicker('hide', 10);
            $('#previewText').text('');
            allFields.val('').removeClass('ui-state-error');
            //$('#updateStatus').fadeOut(2500);
            $('#updateStatus').delay(3000, function() { $('#updateStatus').fadeOut(1000).removeClass('ui-state-highlight'); });
        }
    });

    $('#submitcode').click(function() {
        $('#dialog').dialog('open');
    });

    function limitChars(textid, limit, infodiv) {
        var text = $('#' + textid).val();
        var textlength = text.length;
        if (textlength > limit) {
            $('#' + infodiv).text('You cannot write more then ' + limit + ' characters!');
            $('#' + textid).val(text.substr(0, limit));
            return false;
        }
        else {
            $('#' + infodiv).text('You have ' + (limit - textlength) + ' characters left.');
            return true;
        }
    }

    $(function() {
        $('#description').keyup(function() {
            limitChars('description', 140 - website.val().length - ccode.val().length - 10, 'charlimitinfo');
            $('#previewText').text('Use code ' + ccode.val() + ' at ' + website.val() + ' for ' + description.val());
        })
    });

    $('#expiredate').datepicker({
        inline: true
    });

    jQuery.fn.delay = function(time, func) {
        return this.each(function() {
            setTimeout(func, time);
        });
    };

});