﻿/// <reference path="../jquery-1.4.4.js" />
/// <reference path="~/Scripts/MenuScripts.js" />
var popups = new Array();
var pop_counter = 0;
var mainMindow = $(window);
function PopupObject(title_, width_, target_, height_) {
    this.target = target_;
    this.width = width_;
    this.title = title_;
    var w = mainMindow.width();

    var ht = mainMindow.height();
    this.popupHeight = height_;    
    this.popupTop = ((ht - this.popupHeight) / 2)+ $(window).scrollTop(); //300;
    
    this.left = (w - width_) / 2;
    this.id = 'popup_' + Math.round(1000000 * Math.random());
    this.blokerID = 'popup_blocker';
    this.Index = popups.length;
    this.IsLight = false;
    this.IsRemoveTarget = false;
    popups.push(this);
    pop_counter++;
}
PopupObject.prototype.Close = function (ind, actionSuccess) {

    var pp = popups[ind];
    if (pp.CloseCallBack != null) { pp.CloseCallBack(pp.id, actionSuccess); }
    if (pop_counter == 1) {
        jQuery('#' + pp.blokerID).empty().remove();
    }
    jQuery('#' + pp.id, document.body).empty().remove();
    if (pp.IsRemoveTarget && pp.target != '') {
        jQuery(pp.target).empty().remove();
    }
    pop_counter--;

    //$('#popup_blocker').hide();
    unbindPopupScroll();

}
PopupObject.prototype.Show = function (self, onAddCallback) {
    var html = '';

    var D = document;
    var hh = Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
    //var top = jQuery(document).scrollTop() + (jQuery(window).height() / 2 - 150);
    var w = mainMindow.width();
    var h = mainMindow.height();

    if (pop_counter == 1) { html = '<div class="pop_back_blocker" style="height:' + h.toString() + ';width:' + w.toString() + ';" id="' + this.blokerID + '" ></div>'; }

    html += '<div class="popup_object" id="' + this.id + '" style="position:absolute, width:' + this.width + 'px;height:' + this.popupHeight + 'px;top:' + this.popupTop + 'px;left:' + this.left + 'px;">';


    if (this.IsLight) {
        html += '<div class="popup_caption light_bg">';
        html += '<div class="popup_caption_close light_bg">';
    }
    else {
        html += '<div class="popup-caption">';
        html += '<div class="popup-caption-close">';
    }

    html += '<a class="main-sprite" onclick="PopupObject.prototype.Close(\'' + this.Index + '\', false)"></a>';
    html += '</div>';

    if (this.IsLight) {
        html += '<div class="popup_caption_title light_bg" style="width:' + (this.width - 45) + 'px;">';
    }
    else {
        html += '<div class="popup-caption-title" style="width:' + (this.width - 45) + 'px;">';
    }
    html += this.title;
    html += '</div>';
    html += '</div>';

    if (this.IsLight) {
        html += '<div class="popup_content">';
    }
    else {
        html += '<div class="popup-content">';
    }

    if (this.target != '') {
        html += (jQuery(this.target).html());
    } else {
        alert('please specify selector for popup');
        return;
    }

    html += '</div>'; //end popup-content    
    html += '</div>'; //end popup_object

    jQuery('body').append(html);

    //add indicator
    $("input:text").keyboardLayout();

    var popindex = this.Index;
    var elem = jQuery('#' + this.id);


    bindPopupScroll(elem);


    elem.find('#ok_button').click(function () {
        PopupObject.prototype.Close(popindex, false);

    });
    elem.find('#add_button').click(function () {
        var success = false;
        var duplicate = false; //to check for playlist with the same name
        var entityId = elem.find('input[name=entity_id]').val();
        var entityType = elem.find('input[name=entity_type]').val();
        var playlistName = elem.find('input[name=new_playlist_name]').val();
        var objectId = elem.find('input[name=object_id]').val();

        if (playlistName != null && playlistName != '') {
            //Check if playlist with the same name already exists            
            //            jQuery.each(elem.find('.combo-option'), function () {
            //                if (jQuery(this).text() == playlistName) {
            //                    duplicate = true;
            //                    alert("השם שבחרת כבר קיים,\r\nבחר שם אחר");
            //                    return;
            //                }
            //            });
            if (!duplicate) {
                success = PostAddToPlaylist(entityId, entityType, null, playlistName);

                if (success == true && newPlaylistId > 0) {
                    //new playlist created, need to add it to popup drop down items
                    var content = "<a class=\"combo-option twelve regular\" onclick=\"ChooseOption(this);jQuery(this).closest('.combo-container').find('#selected_playlist_id').val(jQuery(this).next().val());\" id=\"" + newPlaylistId + "\">" + playlistName + "</a><input type=\"hidden\" value=\"" + newPlaylistId + "\"/>";
                    jQuery('.addtoplaylist_object').find('.combo-options').append(content);
                }
            }
        }
        else {
            var selectedPlaylistName = elem.find(".combo-button-text").find(".selected-text").text();
            var $selectedPlaylistLink = elem.find('.combo-option').filter(function () {
                if ($(this).text() == selectedPlaylistName) {
                    return true;
                }
            });

            var playlistId = $selectedPlaylistLink.next().val();

            if (playlistId != null && playlistId != '')
                success = PostAddToPlaylist(entityId, entityType, playlistId, null);
        }
        if (!duplicate)
            PopupObject.prototype.Close(popindex, success);

        if (success && self != undefined && self != null && onAddCallback != undefined && onAddCallback != null) {
            onAddCallback(self);
        }

        if (success && popups[popindex].button) {
            var button = jQuery(popups[popindex].button);
            changeDropMenuPopUp(objectId, true, true);
            if (button.hasClass('add-button-nofloat'))
                button.removeClass('.add-button-nofloat').addClass('subtract-button-nofloat');
            else
                if (button.hasClass('album-add-button'))
                    button.removeClass('.album-add-button').addClass('vert-subtract-button-nofloat');
        }
    });
    elem.find('#cancel_button').click(function () {
        PopupObject.prototype.Close(popindex, false);
    });
}
PopupObject.prototype.ShowButtonPop = function (text, buttons) {
    var html = '';

    var D = document;
    var hh = Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
    //var top = jQuery(document).scrollTop() + (jQuery(window).height() / 2 - 150);
    if (pop_counter == 1) { html = '<div class="pop_back_blocker" style="height:' + GetDocumentHeight(true) + ';width:' + GetDocumentWidth(true) + ';" id="' + this.blokerID + '" ></div>'; }

    //html += '<div class="popup_object" id="' + this.id + '" style="width:' + this.width + 'px;top:' + top + 'px;left:' + this.left + 'px;">';
    html += '<div class="popup_object" id="' + this.id + '" style="position:absolute, width:' + this.width + 'px;height:' + this.popupHeight + 'px;top:' + this.popupTop + 'px;left:' + this.left + 'px;">';



    html += '<div class="button-popup-caption">';
    html += '<a class="button-popup-close" onclick="PopupObject.prototype.Close(\'' + this.Index + '\')"></a>';
    html += '</div>';
    html += '<div class="button-popup-content">';
    html += '    <div class="button-popup-content-section twelve regular t3">'
    html += text;
    html += '    </div>';
    html += '        <div style="text-align:center;height:42px;">';
    if (buttons == 1) {
        html += '            <div class="normal-button button" onclick="" style="float:left;margin:10px 6px 0 136px;">';
        html += '                <div class="normal-button-start button-start combo-sprite"></div>';
        html += '                <div class="normal-button-text button-text combo-sprite">הוסף</div>';
        html += '                <div class="normal-button-end button-end combo-sprite"></div>';
        html += '            </div>';
    }
    else {
        html += '            <div class="normal-button button" onclick="" style="float:left;margin:10px 6px 0 81px;">';
        html += '                <div class="normal-button-start button-start combo-sprite"></div>';
        html += '                <div class="normal-button-text button-text combo-sprite">הוסף</div>';
        html += '                <div class="normal-button-end button-end combo-sprite"></div>';
        html += '            </div>';
        html += '            <div class="normal-button button" onclick="" style="float:left;margin:10px 0 0 0;">';
        html += '                <div class="normal-button-start button-start combo-sprite"></div>';
        html += '                <div class="normal-button-text button-text combo-sprite">ביטול</div>';
        html += '                <div class="normal-button-end button-end combo-sprite"></div>';
        html += '            </div>';
    }

    html += '        </div>';
    html += '</div>'; //end popup-content    

    jQuery('body').append(html);

    var popupElem = jQuery('#' + this.id);
    bindPopupScroll(popupElem); 
}
PopupObject.prototype.CloseCallBack = function (ind, actionSuccess) { }
PopupObject.prototype.GetPopID = function () {
    return this.id;
}
PopupObject.prototype.SetLight = function(isLight) {
    this.IsLight = isLight;
}
PopupObject.prototype.SetRemoveTarget = function (isRemoveTarget) {
    this.IsRemoveTarget = isRemoveTarget;
}

function ShowPopup_addtoplaylist(entityId, entityName, entityType, self, onAddCallback, objectId) {    
    if (entityId == null || entityName == null)
        return;

    if (entityType == null || entityType == '')
        entityType = 'song';

    var directionOpt = containedHebrewLetters(entityName) ? "" : " dir='ltr'";
    var popup = new PopupObject(' הוסף את "<span' + directionOpt +'>' + entityName + '</span>" לפלייליסט', 370, '.addtoplaylist_object', 223);
    if (self) {
        var jself = jQuery(self);
        popup.button = jself.closest('.widget-table-row').find('.add-button-nofloat');
        if (popup.button == null || popup.button.length == 0)
            popup.button = jself.closest('.album1_row_marker').find('.album-add-button');                    
    }
    popup.Show(self, onAddCallback);
    jQuery('#' + popup.GetPopID()).find('input[name=entity_id]').val(entityId);
    jQuery('#' + popup.GetPopID()).find('input[name=entity_type]').val(entityType);
    jQuery('#' + popup.GetPopID()).find('input[name=object_id]').val(objectId);

    return popup;
}

function containedHebrewLetters(text) {
    if (text != null)
    {
        for (var index = 0; index < text.length; index++)
            if (text.charCodeAt(index) >= 0x0591 && text.charCodeAt(index) < 0x05F4)
                return true;
    }
    return false;
}

function ShowPopup_exposeProfile(text) {

    var h = 402;
    if($.browser.msie && $.browser.version == 8)
        h = 405;
    else if ($.browser.msie && $.browser.version == 7)
        h = 388;
    var popup = new PopupObject('', 370, '.exposeprofile_object',h);
    popup.Show();
    var elem = jQuery('#' + popup.GetPopID());
    elem.find('.popup-caption-title').html(elem.find('input[name=popup_title]').val());

    return popup;
}

function ShowPopup_uploadImage() {

    var h = 134;
    if ($.browser.msie && $.browser.version < 9)
        h = 129;
    var popup = new PopupObject('', 370, '.uploadimage_object',h);
    popup.Show();
    var elem = jQuery('#' + popup.GetPopID());
    elem.find('.popup-caption-title').html(elem.find('input[name=popup_title]').val());
    var uploadUrl = "http://" + window.location.host + "/Services/MCMBridge.svc/UploadProfileImage";
    var uploadForm = elem.find('form[name=upload_form]');
    uploadForm.attr('action', uploadUrl);
    uploadForm.submit(function (e) {
        e.preventDefault();
        jQuery.post(jQuery(this).attr("action"), jQuery(this).serialize(), function (json) {
            // handle response
            if (json.Success == true) {
                alert('Upload success');
            }
            else {                
             }
        }, "json");
    });
    return popup;
}

function ShowPopup_button(text, buttons) {
    var popup = new PopupObject("", 370, "",114);
    popup.ShowButtonPop(text, buttons);
}


function bindPopupScroll(popupElem) {
    $(window).bind('scroll', function () {

        var t = ($(window).scrollTop() + popupElem.height() + $(window).height()) / 2;
        var txt = popupElem.find('.popup-caption-title').html();
        
        //otherwise => D
        if (txt == "חשיפת פרופיל אישי")
            t -= popupElem.height() ;

        popupElem.css("top", t + "px");

        //popupElem.css("top", ($(window).scrollTop() + popupElem.position.top())+ "px");


    });

}

function unbindPopupScroll() {

    $(window).unbind('scroll');

}

function ShowPopup_fbDialog() {

    var h = 84;
    if ($.browser.msie && $.browser.version == 7)
        h = 71;
    var txt = '<p>בשל הגבלת זכויות יוצרים לא ניתן לשתף את התוכן המבוקש</p>';
    var popup = new PopupObject(txt, 370, '.uploadimage_object',h);
    popup.Show();

     var elem = jQuery('#' + popup.GetPopID());
     elem.find('.popup-caption-title').html("שיתוף בפייסבוק");
     elem.find('.popup-content').html(txt);


}

var newPlaylistId = '';
function PostAddToPlaylist(_entityId, _entityType, _playlistId, _playlistName) {
    if (_entityId == null || _entityType == null || (_playlistId == null && _playlistName == null))
        return false;

    if (_playlistName != null) {
        _playlistName = encodeURIComponent(_playlistName);
    }

    var _data;
    if (_playlistName != null) {
        //add to new playlist
        _data = '{ "entityId":"' + _entityId + '","entityType":"' + _entityType + '", "playlistId":-1, "newPlaylistName":"' + _playlistName + '" }';
    }
    else {
        //add to existing playlist
        _data = '{ "entityId":"' + _entityId + '","entityType":"' + _entityType + '", "playlistId":' + _playlistId + ', "newPlaylistName":"" }';
    }
    var _success;

    jQuery.ajax({
        cache: false,
        async: false,
        type: "POST",
        url: "http://" + window.location.host + "/Services/MCMBridge.svc/AddToPlaylist",
        data: _data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var result = jQuery.parseJSON(data.d);
            _success = false;
            if (result != null) {
                _success = result.success;
                if( _playlistName != null && result.newplaylistid != undefined && result.newplaylistid != "")
                    newPlaylistId = result.newplaylistid;                
            }
            jQuery.debug("PostAddToPlaylist >> success " + data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            _success = false;
            jQuery.debug("PostAddToPlaylist >> error " + errorThrown);
            logError('PostAddToPlaylist', XMLHttpRequest.statusText, XMLHttpRequest.responseText);
        }
    });    
    return _success;
}
function ShowPopup_errorUploading() {
    var popup = new PopupObject('', 370, '.messagebox_object',114);
    popup.Show();
    var elem = jQuery('#' + popup.GetPopID());
    elem.find('.popup-caption-title').html(elem.find('input[name=popup_title]').val());
}

var MessageBox = {
    Show: function (body) {
        this.ShowDefault({
            title: '',
            body: body,
            width: 370,
            isScroll: false,
            closeCallBack: null
        });
    },
    ShowCustomWithAction: function (title, body, width, closeCallBack, isScroll) {
        this.ShowDefault({
            title: title,
            body: body,
            width: width,
            isScroll: isScroll,
            closeCallBack: closeCallBack
        });
    },
    ShowCustom: function (title, body, width, isScroll) {
        this.ShowDefault({
            title: title,
            body: body,
            width: width,
            isScroll: isScroll,
            closeCallBack: null
        });
    },
    ShowDefault: function (details) {
        var title = details.title;
        var body = details.body;
        var width = details.width;
        var isScroll = details.isScroll;
        
        var html = '';
        html += '<div class="popup_window message-box">';
        html += '   <div class="popup_content" style="" >';
        html += '       <div style="padding-top: -1px; padding-bottom: 28px; padding-left: 40px; padding-right: 40px; max-height:200px; overflow-x: visible; overflow-y: ' + ((isScroll) ? 'scroll' : 'auto') + ';">' + body + '</div>';
        html += '   </div>';
        html += '   <div class="popup_buttons" style="text-align: center;">';
        html += '       <div id="ok_button" class="normal-button button">';
        html += '           <div class="normal-button-start button-start combo-sprite"></div>';
        html += '           <div class="normal-button-text button-text combo-sprite">אישור</div>';
        html += '           <div class="normal-button-end button-end combo-sprite" ></div>';
        html += '       </div>';
        html += '   </div>';
        html += '</div>';
        
        var target = document.body;
        jQuery(target).append(html);
        var popup = new PopupObject(title, width, '.message-box',111);
        popup.SetLight(true);
        popup.SetRemoveTarget(true);
        popup.CloseCallBack = details.closeCallBack;
        popup.Show();
    }
};

/*
var MessageBox = {
    Show: function (body) {
        this.ShowDefault({
            title: '',
            body: body,
            width: 370,
            isScroll: false,
            closeCallBack: null
        });
    },
    ShowCustomWithAction: function (title, body, width, closeCallBack, isScroll) {
        this.ShowDefault({
            title: title,
            body: body,
            width: width,
            isScroll: isScroll,
            closeCallBack: closeCallBack
        });
    },
    ShowCustom: function (title, body, width, isScroll) {
        this.ShowDefault({
            title: title,
            body: body,
            width: width,
            isScroll: isScroll,
            closeCallBack: null
        });
    },
    ShowDefault: function (details) {
        var title = details.title;
        var body = details.body;
        var width = details.width;
        var isScroll = details.isScroll;
        var closeCallBack = details.closeCallBack;

        var target = document.body;
        var html = '';
        this.Id = 'popup_window_' + Math.round(999999 * Math.random()).toString();
        this.blokerID = 'popup_blocker';

        var docWidth = mainMindow.width();
        var docHeight = mainMindow.height();

        html = '<div class="pop_back_blocker" style="height:' + GetDocumentHeight(true) + ';width:' + docWidth.toString() + 'px;" id="' + this.blokerID + '"></div>';
        html += '<div class="popup_window message-box" id = "' + this.Id + '" style="width: ' + width.toString() + 'px; top: 200px; left: ' + ((docWidth - width) / 2).toString() + 'px;">';
        html += '<div class="popup_caption" style="text-align: center;">';
        html += '<div class="popup_caption_close"><a class="main-sprite" onclick="MessageBox.Close(' + id + ',' + closeCallBack + ')"></a></div>';
        html += '<div style="WIDTH: ' + (width - 34) + 'px" class=popup_caption_title>' + title + '</div>';
        html += '</div>';
        html += '<div class="popup_content" style="" >';
        html += '<div style="padding-top: -1px; padding-bottom: 28px; padding-left: 40px; padding-right: 40px; max-height:200px; overflow-x: visible; overflow-y: ' + ((isScroll) ? 'scroll' : 'auto') + ';">' + body + '</div>';
        html += '</div>';
        html += '<div class="popup_buttons" style="text-align: center;">';
        html += '   <div class="normal-button button" onclick="MessageBox.Close(' + id + ', ' + closeCallBack + ')">';
        html += '       <div class="normal-button-start button-start combo-sprite"></div>';
        html += '       <div class="normal-button-text button-text combo-sprite">אישור</div>';
        html += '       <div class="normal-button-end button-end combo-sprite" ></div>';
        html += '   </div>';
        html += '</div>';
        html += '</div>';
        jQuery(target).append(html);
    },
    Close: function (popupId, closeCallBack) {

        jQuery('#popup_blocker_' + popupId).empty().remove();

        jQuery('#popup_window_' + popupId).empty().remove();
        if (closeCallBack != null && closeCallBack != undefined) {
            closeCallBack();
            closeCallBack = null;
        }
    },
    GetId: function () {
        return this.id;
    }
};
*/

mainMindow.resize(function () {
    if (popups != null && popups != undefined) {
        for (var index = 0; index < popups.length; index++) {
            var popup = popups[index];
            if (popup != undefined) {
                CentredPoup($('#' + popup.GetPopID()));
            }
        }
    }    
    $(".message-box").each(function (i) {
        CentredPoup($(this));
    });

});
function CentredPoup(popWindow) {

    var docWidth = mainMindow.width();
    var docHeight = mainMindow.height();

    var popupHeight = popWindow.height();
    var popupWidth = popWindow.width();

    if (popupWidth != undefined) {
        var popBlocker = $('.pop_back_blocker');
        popBlocker.width(docWidth);
        popBlocker.height(docHeight);
        var newLeft = (docWidth - popupWidth - 20) / 2;
        popWindow.offset({ left: newLeft });
    }
}
function UpdatePlaylistName(oldPlaylistName, newPlaylistName) {
    var $addToPlaylist = jQuery('.addtoplaylist_object');
    if ($addToPlaylist == null && $addToPlaylist == undefined)
        return;
    var $selectedPlaylistElement = $addToPlaylist.find(".combo-button-text").find(".selected-text");
    if ($selectedPlaylistElement.text() == oldPlaylistName)
        $selectedPlaylistElement.text(newPlaylistName);
        $addToPlaylist.find('.combo-option').each(function () {
        if (jQuery(this).text() == oldPlaylistName) {
            jQuery(this).text(newPlaylistName);
            return;
        }
    });
}
