﻿__isUpdatingMessageCount = false;
_jNewMsgs = null;
jQuery(document).everyTime('3s', 'new-msg', function () {
    if (__isUpdatingMessageCount || !_jNewMsgs)
        return;
    __isUpdatingMessageCount = true;
    jQuery.getJSON(__root + 'Messages/Run/GetNewCount', function (d) {
        if (d.state == 'ok' && d.count && d.count > 0) {
            _jNewMsgs.find('a').attr('title', 'You have ' + d.count + ' unread message' + (d.count > 1 ? 's' : ''));
            _jNewMsgs.css('display', 'inline');
        }
        else
            _jNewMsgs.css('display', 'none');
        __isUpdatingMessageCount = false;
    });
});

searchAreaNames = {0:'Search', 1:'Search Bars', 2:'Search People', 3:'Search Articles'};

function searchQueryChanged() {
    var _this = jQuery('#search_input');
    var v = _this.val();
    if (!v || v.length == 0)
        return false;
    for (var i in searchAreaNames)
        if (v == searchAreaNames[i])
        return false;
    return true;
}

function logout() {
    jQuery(document).stopTime('new-msg');
    jQuery.get(__root + 'Account/Run/Logout', {}, function (resp) {
        if (resp == 'ok')
            window.location.reload();
    })
}

function selSearchArea(num) {
    searchAreaNum = num;
    jQuery('#where_to_search').val(num);
    setQueryInputBGText();
    jQuery('#search_popup').jqmHide();
}
function setQueryInputBGText() {
    var _this = jQuery('#search_input');
    if (!searchQueryChanged()) {
        _this.val(searchAreaNames[searchAreaNum]);
        _this.css('color', '#999999');
    } else
        _this.css('color', '#fff');
}

jQuery(document).ready(function () {
    _jNewMsgs = jQuery('#new_messages_alert');

    /* process images */
    //    jQuery('#latest_singles.box.index.userslist ul li .png a img').unbind('load').load(function () {
    //        var jQuerythis = jQuery(this);
    //        var _img = new Image();
    //        _img.src = jQuerythis.attr('src');
    //        var _ratio = _img.width / _img.height;
    //        var _width;
    //        var _height;
    //        if (_img.width < _img.height) {
    //            _width = 88;
    //            _height = Math.round(_width / _ratio);
    //        } else {
    //            _height = 105;
    //            _width = Math.round(_height * _ratio);
    //        }
    //        jQuerythis.attr('width', _width).attr('height', _height).css({ width: _width + 'px', height: _height + 'px' });
    //    });
    /* end process images */


    jQuery('#search_popup').jqm({ overlay: 1, modal: false });

    jQuery('#search_popup_btn').click(function () {
        jQuery('#search_popup').jqmShow();
    });

    setQueryInputBGText();

    jQuery('#search_input')
    .focus(function () {
        var _this = jQuery(this);
        if (!searchQueryChanged()) {
            _this.val('');
            _this.css('color', '#fff');
        }
    })
    .blur(function () {
        setQueryInputBGText();
    })
    .autocomplete({ source: __root + 'Search/Run/Suggest', minLength: 2 });

    jQuery('.ajax-popup-opener').click(function (e) {
        return openPopup(jQuery(this).attr('href'));
    });

    jQuery('.section-title a').click(function () {
        var sectionContent = jQuery(this).parents('.section').find('.section-content');
        if (sectionContent.css('display') == 'none') {
            sectionContent.slideDown(200);
        } else {
            sectionContent.slideUp(200);
        }
        return false;
    });

    BindDescriptionUpdater = function () {
        jQuery('.image-description-container form').each(function () {
            var _this = jQuery(this);
            var _msgHolder = _this.find('.update-result');
            _this.ajaxForm({
                target: null,
                beforeSerialize: function () {
                    _msgHolder.show().html("<img src='" + __root + "Content/images/load_circle.gif' />");
                },
                success: function (data) {
                    _msgHolder.html(data['Message']);
                    _msgHolder.css("color", data['MsgColor']);
                    if (data['Success']) {
                        hideMsg = function () {
                            _msgHolder.hide();
                        }
                        setTimeout(hideMsg, 3000);
                    }
                }
            });
        });
    }
    BindDescriptionUpdater();

    BindPhotosManagementList = function () {
        jQuery('a.photos-management-link').unbind('click').click(function () {
            if (jQuery(this).is('.confirmed-action') && !confirm('Are you sure?')) {
                return false;
            }
            var container = jQuery('#photosManagementList');
            container.html("<div style='text-align:center;padding:20px;float:left;'><img src='" + __root + "Content/images/load_circle.gif' /></div>");
            var _url = jQuery(this).attr('href');
            jQuery.get(_url, function (data) {
                container.html(data);
                BindPhotosManagementList();
                BindDescriptionUpdater();
            });
            return false;
        });
    }
    BindPhotosManagementList();


    jQuery('.editStatusLink').click(function () {
        jQuery('#statusEditor').show();
        jQuery(this).hide();
        return false;
    });

    jQuery('#submitStatusEdit').click(function () {
        jQuery(this).parents('form').submit();
        return false;
    });

    jQuery('#cancelStatusEdit').click(function () {
        jQuery('#statusEditor').hide();
        var editStatusLink = jQuery('.editStatusLink');
        if (editStatusLink.is('.current-status')) {
            jQuery('#NewStatus').val(jQuery('.editStatusLink').text());
        }
        else {
            jQuery('#NewStatus').val('');
        }
        editStatusLink.show();
        return false;
    });

    jQuery('#statusEditor form').submit(function () {
        var _url = jQuery(this).attr('action');
        var _data = {
            barId: jQuery(this).find('#BarID').val(),
            newStatus: jQuery(this).find('#NewStatus').val()
        };
        jQuery('#statusEditor').find("form").hide();
        jQuery('#statusEditor').find("#editStatusLoading").show();
        jQuery.getJSON(_url, _data, function (data) {
            jQuery('#statusEditor').hide();
            jQuery('.editStatusLink').show();
            if (data['statusIsEmpty']) {
                jQuery('#NewStatus').val('');
                jQuery('.editStatusLink').text('Edit status message');
                jQuery('.editStatusLink').removeClass('current-status').addClass('edit-empty-status');
            }
            else {
                jQuery('#NewStatus').val(data['status']);
                jQuery('.editStatusLink').text(data['status']);
                jQuery('.editStatusLink').removeClass('edit-empty-status').addClass('current-status');
            }
            jQuery('#statusEditor').find("form").show();
            jQuery('#statusEditor').find("#editStatusLoading").hide();
        });
        return false;
    });

    (function ($) {

        var $ReportUserComment = $('textarea#ReportUserComment');
        if ($ReportUserComment.length > 0) {
            var SetCharCounts = function (input) {
                var $this = $(input);
                var _val = $this.val();
                var _rem = 150 - _val.length;
                if (_rem < 0) {
                    _rem = 0;
                }
                $this.val(_val.substring(0, 150));
                $('#ReportUserCommentCharsLeft').text(_rem);
            }
            $ReportUserComment.unbind('keyup').keyup(function () { SetCharCounts(this); }).each(function () { SetCharCounts(this); });
        }

    })(jQuery);
});

function show_hide(el) {
    if (!el || !el.id) return null;
    var d = document.getElementById(el.id + '_content');
    if (!d) return null;
    d = jQuery(d);
    if (d.css('display') == 'none') {
        d.show();
        jQuery(el).attr('class', 'expanded-content-header');
    }
    else
    {
        d.hide();
        jQuery(el).attr('class', 'collapsed-content-header');
    }
    return null;
}

function openPopup(_url, callback) {
    if (jQuery('#__popupHolder').css('display') != 'none') {
        jQuery('#__popupHolder').jqmHide();
    }
    jQuery('#__popupHolder').jqm({
        ajax: _url,
        modal: true,
        onShow: function (hash) {
            hash.w.html("<div style='text-align:center;padding:20px;'><img src='" + __root + "Content/images/load_circle.gif' /></div>").show();
        },
        onLoad: function (hash) {
            //FB.init(_fb_apikey, __root + "fb_point/xd_receiver.htm");
            InitFacebook();
            if (callback) callback(hash);
        }
    });
    jQuery('#__popupHolder').jqmShow();
    jQuery('#__popupHolder').draggable({handle: '.popup-title'});
    return false;
}

function reloadLoginInfo() {
    jQuery('#login_info').load(__root + 'Account/LoginInfo');
}

function newCaptcha(ssnHolderSel, imgSel) {
    var ssnid = jQuery(ssnHolderSel).val();
    jQuery.getJSON(__root + 'Account/Run/GetNewCaptcha', { sessionId: ssnid }, function(data, status) {
        if (status == 'success' && data.state == 'ok') {
            ssnid = data.ssnID;
            jQuery(ssnHolderSel).val(ssnid);
            jQuery(imgSel).attr('src', __root + 'Account/Captcha/' + ssnid);
        }
    })
}

// Bas list
function selInPopup(url, idPfx, cls, callback) {
    return openPopup(url, function () {
        jQuery.each(jQuery("." + cls), function () {
            jQuery('#p_' + this.id).attr('checked', this.checked);
        });
        if (callback) callback();
    });
}

function selFromPopup(idPfx, cls) {
    jQuery.each(jQuery(".p_" + cls), function() {
        jQuery('#' + this.id.substring(2)).attr('checked', this.checked);
    });
    jQuery('#__popupHolder').jqmHide();
}

function selAll(cls, val) {
    var hds = jQuery('.' + cls);
    jQuery.each(hds, function() {
        this.checked = val;
    });
}

function closeSelValsPopup(idpfx, cls, opt_id) {
    selFromPopup(idpfx, cls);
    onCloseSelPopup(opt_id, cls);
    jQuery('#__popupHolder').jqmHide();
}

function setDetail(cntrlr, id, prm) {
    plist.cnUrl = __root + 'Admin/' + cntrlr + '/';
    if (cntrlr.length == 0) {
        jQuery("#detail_content").html('');
        return;
    }

    if (!prm)
        prm = 'pid';;

    plist.masterFltr = {};
    if (id)
        plist.masterFltr[prm] = id;
        
    plist.renewList();
}

function setVoteForArticle(id, v) {
    jQuery.getJSON(__root + 'Buzz/SetVote/' + id, { v: v }, function (data, status) {
        if (status != 'success' || !data.msg) return;
        if (data.msg == 'need login')
            loginForm.show();
        if (data.msg == 'ok') {
            jQuery('#vote' + id).load(__root + 'Buzz/VotesCount/' + id);
            jQuery.growl('Information', 'Thank you for your vote');
        }
    });
}

function rightMapInit() {
    var latlng = new google.maps.LatLng(40.764676, -73.973366);
    var myOptions = {
        zoom: 14,
        center: latlng,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    r_map = new google.maps.Map(document.getElementById("BarLocation"), myOptions);
}

r_marker = null;
function showOnMap(lat, lng, title) {
    var ll = new google.maps.LatLng(lat, lng);
    if (!r_marker)
        r_marker = new google.maps.Marker({
            position: ll,
            map: r_map,
            title: title
        });
    else {
        r_marker.setPosition(ll);
        r_marker.setTitle(title);
    }
    r_map.setCenter(ll);
    r_map.setZoom(14);
}

function attachInfoWindow(marker, num) {
    google.maps.event.addListener(marker, 'click', function() {
        if (!mrkrs[num].content) {
            infowin.setContent('<div style="width:200px;text-align:center;padding-top:20px;"><img src="' + __root + 'content/images/load_circle.gif" alt="loading..."/></div>');
            jQuery.get(__root + 'Bar/PopupInfo/' + mrkrs[num].id, null, function(data) {
                infowin.setContent(data);
                mrkrs[num].content = data;
            });
        } else {
            infowin.setContent(mrkrs[num].content);
        }
        infowin.open(map, marker);
    });

}


function IncShareCount(type, id) {
    jQuery.get(__root + "Buzz/Run/IncShare", { type: type, buzzID: id }, function(data, status) {
        if (status == "success" && data && data.fb && data.twitter && data.email) {
            jQuery("#fb_share_count").html(data.fb);
            jQuery("#twitter_share_count").html(data.twitter);
            jQuery("#email_share_count").html(data.email);
        }
    });
}

function addNewBuzzComment() {
    var jqf = jQuery('#add_comment_form');
    var jqt = jQuery('#Text');
    var options = {
        success: function(resp) {
            if (resp == 'need login')
                loginForm.show();
            if (resp == 'ok')
                location.reload();
        }
    };
    jqf.ajaxSubmit(options);
}

function removeComment(id) {
    if (confirm('Remove this post?'))
        jQuery.get(__root + 'Buzz/Run/RemoveComment', { commentID: id }, function(resp) {
            if (resp == "ok") location.reload();
        })
}

function banUser(id, name) {
  if (confirm('Do you want to disable posting comments for ' + name + '?'))
    jQuery.get(__root + 'Buzz/Run/BanUser', { userID: id }, function(resp) {
        if (resp == "ok") alert(name + ' is banned');
    })
}

function findBarMapInit() {
    var latlng = new google.maps.LatLng(40.764676, -73.973366);
    var myOptions = {
        zoom: 14,
        center: latlng,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    f_map = new google.maps.Map(document.getElementById("map-holder"), myOptions);
    f_marker = null;
}

function setFindBarMapMarker(lat, lng, name, fixedMarker) {
    if (lat == 0 || lng == 0) return;
    if (!f_map)
        findBarMapInit();
    var ll = new google.maps.LatLng(lat, lng);
    var dragg = true;
    if (fixedMarker)
        dragg = false;
    if (!f_marker) {
        f_marker = new google.maps.Marker({
            position: ll,
            map: f_map,
            title: name,
            draggable: dragg,
            icon: 'http://www.google.com/mapfiles/arrow.png'
        });
        google.maps.event.addListener(f_marker, 'dragend', function(event) {
            jQuery("#Latitude").val(event.latLng.lat());
            jQuery("#Longitude").val(event.latLng.lng());
        });        
    } else {
        f_marker.setPosition(ll);
        if (name)
            f_marker.setTitle(name);
    }
    f_map.setCenter(ll);
    f_map.setZoom(17);
}

function findLatLngByAddr() {
    var addr = {
        addr1: jQuery('#Address1').val(),
        addr2: jQuery('#Address2').val(),
        city: jQuery('#City').val(),
        state: '',
        zip: jQuery('#Zip').val()
    };
    jQuery.getJSON(__root + 'BarOwner/Run/FindCoords', addr, function(data) {
        if (data.state == 'ok') {
            setFindBarMapMarker(data.Latitude, data.Longitude);
            jQuery('#Latitude').val(data.Latitude);
            jQuery('#Longitude').val(data.Longitude);
        };

    });
}

function delImg(id) {
    if (confirm('Delete image?'))
        jQuery('#image_list').load(__root + 'Profile/Run/DeleteImage', { imgId: id });
}

function CheckBoxGroup(cls, pfx) {
    var ncb = jQuery('#' + pfx + '_all');

    var checkNone = function () {
        var none = true;
        jQuery('.' + cls).each(function () {
            if (this.checked)
                none = false;
        });
        ncb.attr('checked', none);
    }

    checkNone();
    ncb.change(function () {
        if (ncb.attr('checked'))
            jQuery('.' + cls).attr('checked', false);
        checkNone();
    });

    jQuery('.' + cls + ',#' + pfx + '_all').change(checkNone);
} 

var W3CDOM = (document.createElement && document.getElementsByTagName);


function initf() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	var image = document.createElement('img');
	image.src= __root + 'content/images/buttons/browse.png';
	fakeFileUpload.appendChild(image);
	fakeFileUpload.appendChild(document.createElement('input'));
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].getAttribute('noscript')) continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		if (x[i].value)
			x[i].onchange();
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}

function commingSoon(msg) {
    openPopup(__root + 'Home/Load/' + msg);
}
