﻿
//autofill
function autoFill(id, v) {

    if ($(id).val() == "" || $(id).val() == v) {
        $(id).css({ color: "#b2adad" }).attr({ value: v }).focus(function() {
            if ($(this).val() == v) {
                $(this).val("").css({ color: "#333" });
            }
        }).blur(function() {
            if ($(this).val() == "") {
                $(this).css({ color: "#b2adad" }).val(v);
            }

        });
    }

}


//querystring
location.querystring = (function() {

    // The return is a collection of key/value pairs
    var queryStringDictionary = {};

    // Gets the query string, starts with '?'
    var querystring = decodeURI(location.search);

    // document.location.search is empty if no query string
    if (!querystring) {
        return {};
    }

    // Remove the '?' via substring(1)
    querystring = querystring.substring(1);

    // '&' seperates key/value pairs
    var pairs = querystring.split("&");

    // Load the key/values of the return collection
    for (var i = 0; i < pairs.length; i++) {
        var keyValuePair = pairs[i].split("=");
        queryStringDictionary[keyValuePair[0]]
                        = keyValuePair[1];
    }

    // toString() returns the key/value pairs concatenated
    queryStringDictionary.toString = function() {

        if (queryStringDictionary.length == 0) {
            return "";
        }

        var toString = "?";

        for (var key in queryStringDictionary) {
            toString += key + "=" +
                        queryStringDictionary[key];
        }

        return toString;
    };

    // Return the key/value dictionary

    return queryStringDictionary;
})();

//z-index
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

//global Jquery
$(document).ready(function () {
    autoFill($("#mainSearchInput"), "Product Search");
    autoFill($("#KeyWord"), "Search");
    autoFill($("#Keyword"), "Key Word");
    autoFill($("#keyword"), "Key Word");
    autoFill($("#SearchUser_Keyword"), "Key Word");
    autoFill($("#SearchVendor_Keyword"), "Key Word");
    autoFill($("#SearchProduct_Keyword"), "Key Word");
    autoFill($("#SearchEvent_Keyword"), "Key Word");

    $('a:has(img)').addClass('nostyle');

    $('.datepicker').datepicker({ beforeShow: function () { $('#ui-datepicker-div').maxZIndex(); },
        dateFormat: 'm/d/yy'
    });

    $(".zebra > tbody > tr:even").addClass("even");

    $('.confirm').click(function () {
        var answer = confirm('Are you sure you want to delete this ' + $(this).attr('title'));
        return answer;
    });

    $('.confirmMessage').click(function () {
        var answer = confirm($(this).attr('title'));
        return answer;
    });

    ////////////////////////////////////////////////////////////

    // Dialogs			
    $('#dialog').dialog({
        autoOpen: false,
        width: 800,
        modal: true
    });

    $('#dialog_ck').dialog({
        autoOpen: false,
        width: 800,
        modal: true,
        open: function () {
            $(this).find(".ckeditor_dialog").ckeditor();
        },
        close: function () {
            $(this).find(".ckeditor_dialog").ckeditorGet().destroy();
        }
    });

    $('.dialog_replyComment').dialog({
        autoOpen: false,
        width: 600,
        modal: true
    });

    $('#dialog_comment').dialog({
        autoOpen: false,
        width: 600,
        modal: true
    });

    $('#dialog_video').dialog({
        autoOpen: false,
        width: 600,
        modal: true
    });

    $('.dialog_video').dialog({
        autoOpen: false,
        width: 600,
        modal: true
    });

    $('#dialog_sendMessage').dialog({
        autoOpen: false,
        width: 600,
        modal: true
    });

    ////////////////////////////////////////////////////////////

    // Dialog Link
    $('#dialog_link').click(function () {
        $('#dialog').dialog('open');
        return false;
    });

    // Dialog Link
    $('#dialog_ck_link').click(function () {
        $('#dialog_ck').dialog('open');
        return false;
    });

    // Dialog Link -- Reply to a Comment
    $('.dialog_replyComment_link').click(function () {
        $('#dialog_replyComment_' + $(this).attr("id")).dialog('open');
        return false;
    });

    // Dialog Link -- comment
    $('#dialog_comment_link').click(function () {
        $('#dialog_comment').dialog('open');
        return false;
    });

    // Dialog Link -- video
    $('#dialog_video_link').click(function () {
        $('#dialog_video').dialog('open');
        return false;
    });

    $('.dialog_video_link').click(function () {
        var videoID = $(this).attr('id');
        $('#dialog_video_' + videoID).dialog('open');
        return false;
    });


    $('#dialog_sendMessage_link').click(function () {
        $('#dialog_sendMessage').dialog('open');
        return false;
    });


    ////////////////////////////////////////////////////////////


    $(function () {
        $(function () {
            $('.lightbox').lightBox({
                imageLoading: '/Content/images/lightbox-ico-loading.gif',
                imageBtnClose: '/Content/images/lightbox-btn-close.gif',
                imageBtnPrev: '/Content/images/lightbox-btn-prev.gif',
                imageBtnNext: '/Content/images/lightbox-btn-next.gif',
                imageBlank: '/Content/images/lightbox-blank.gif'
            });
        });

    });

    $("#tabContainer").tabs();
    $(".tabContainer").tabs();

    $('.tabContainer').tabs({
        show: function (event, ui) {
            $('#CalendarView').fullCalendar('render');
        }
    });

    $('#tabContainer').tabs({
        show: function (event, ui) {
            $('#CalendarView').fullCalendar('render');
        }
    });

    //$('a.qtip[title]').qtip({ style: { name: 'light', tip: true} })

    $(".likeLink").live('click', function (event) {
        var id = $(this).attr("title");
        var link = $(this).attr("href");

        event.preventDefault();

        $.get(link, function (data) {

            if (data == 'addLikeLink') {
                $('span#' + id).replaceWith('<span id=\"' + id + '\"><a href=\"' + link + '\" class=\"likeLink nolike\" title=\"' + id + '\">Like</a></span>');
            }
            else if (data == 'addNoLikeLink') {

                $('span#' + id).replaceWith('<span id=\"' + id + '\">You Like This - <a href=\"' + link + '\" class=\"likeLink like\" title=\"' + id + '\">Un-Like</a></span>');
            }
            else {
                alert(data);
            }

        });
    });

    $("#ChooseVendor").change(function () {
        var id = $(this).val();

        if (parseInt(id) > 0) {

            //switch the vendor
            $.ajax({
                type: "GET",
                url: "/Home/SetVendor/" + id,
                error: function (msg) {
                    alert("error: " + msg);
                },
                success: function (msg) {
                    window.location = "/";
                }
            });
        }
    });

    $(".addFriend").click(function () {
        var userid = $(this).attr('id');
        $.get("/Application/AddFriend/" + userid, function (data) {

            if (data == 'success') {
                $("#profileAddFriend").html("<img src=\"/Content/images/LinkIcons/personal.png\" alt=\"\"> The status of your friend request is: Pending");
            }
            else {
                alert(data);
            }

        });
        return false;
    });

    $(".acceptFriend").click(function () {
        var id = $(this).attr('id');
        $.get("/Application/AcceptFriend/" + id, function (data) {

            if (data == 'success') {
                $("#acceptreply_" + id).html("You are now friends.");
            }
            else {
                alert(data);
            }

        });
        return false;
    });

    $(".declineFriend").click(function () {
        var id = $(this).attr('id');
        $.get("/Application/DeclineFriend/" + id, function (data) {

            if (data == 'success') {
                $("#declinereply_" + id).html("The request has been declined.  The requester has not been notified, although the invite will no longer show as pending.");
            }
            else {
                alert(data);
            }

        });
        return false;
    });

    $("a.video_small").embedly({ maxWidth: 200, wrapElement: 'div', method: "replace" });
    $("a.video").embedly({ maxWidth: 530, wrapElement: 'div', method: "replace" });

    $('.imageBrowse').popupWindow({
        centerBrowser: 1,
        windowURL: '/Profile/CommentImage/',
        windowName: 'Gallery',
        height: 500,
        width: 900
    });


    $('#loading')
    .hide()  // hide it initially
    .ajaxStart(function () {
        $(this).show();
    })
    .ajaxStop(function () {
        $(this).hide();
    });

    //var randomImages = ['background_3.jpg', 'background_2.jpg', 'background_1.jpg'];
    //var rndNum = Math.floor(Math.random() * randomImages.length);
    //$("body").css("background-image", "url(/Content/images/Backgrounds/" + randomImages[rndNum] + ")");

    jQuery(function ($) {
        $(".maskDate").mask("99/99/9999");
        $(".maskPhone").mask("(999) 999-9999");
        $(".maskZip").mask("99999");
    });

    $('a[rel*=external]').click(function () {
        var valueArray = $(this).attr('name');
        var href = $(this).attr('href');

        $.post("/Application/TrackAdClick/", { id: valueArray }, function (data) {
            $(this).unbind("click");
            window.location = href;
        });

        return false;
    });

});
