// Prompt A User To Save Changes Before Leaving Page
var isDirty = false;
var confirmExitMsg = 'You haven\'t saved your changes.';

$(document).ready(function() {
	// TABS
	$("#tabs").tabs({
		spinner: 'Loading...',
		load: function(event, ui) {
			$( "#tabs .ui-state-active span").html('');
		},
		selected: -1,
        cache: $.browser.msie ? false : true,
        ajaxOptions:{cache: $.browser.msie ? false: true}
	});

	$('.fn_showEditPanel').die('click');
	$('.fn_showEditPanel').live('click', function() {
		$('.viewPanel').hide();
		$('.editPanel').show();
	});

	$('.fn_showViewPanel').die('click');
	$('.fn_showViewPanel').live('click', function() {
		$('.editPanel').hide();
		$('.viewPanel').show();
	});

    $('.mainTabs .dashboard').hover(function() {
        if ($.browser.msie) {
            $(this).find('ul')
                    .show();
        } else {
            $(this).find('ul')
                    .attr('style', '')
                    .css('display', 'none')
                    .stop()
                    .slideDown();
        }
    }, function() {
        if ($.browser.msie) {
            $(this).find('ul')
                    .hide();
        } else {
            $(this).find('ul')
                    .stop()
                    .slideUp('fast');
        }
    });


});


function init_js() {

	// hide editPanels
	$('.editPanel').hide();
	$('.viewPanel').show();

	// Prompt A User To Save Changes Before Leaving Page
	confirmExit();
    isDirty = false

	// GENERIC TOOLTIPS

	var tt_X;
	var tt_Y;
    var w = $('#page');
	$(".tooltipWrap").mousemove(function(e) {

        var w_pos = w.position();

        tt_X = e.pageX - w_pos.left + 20;	tt_Y = e.pageY;
		w.find('.tooltip').css({top:tt_Y+"px",left:tt_X+"px"});
	});
	$(".tooltipWrap").hover(function(e){
		var txt = $(this).attr('alt');
		if (txt) {	w.append("<div class='tooltip'>"+txt+"</div>");
		} 
	}, function(){
		w.find('.tooltip').remove();
	});


}

function setBusinessHourPanel() {
	$('input#enabled').each(function(){
		if($(this).is(':checked')) {
			$('#enabledDetails').show();
		} else {
			$('#enabledDetails').hide();
		}
	});

	$('input#enabled').live('click', function() {
		if($(this).is(':checked')) {
			$('#enabledDetails').slideDown();
		} else {
			$('#enabledDetails').slideUp();
		}
	});

}

function confirmExit() {
	// Prompt A User To Save Changes Before Leaving Page
	$(':input').live('change', function() {
        if(!isDirty){
            isDirty = true;
        }
    });
    window.onbeforeunload = function(){
        if(isDirty){
//            return confirmExitMsg;
        }
    };
}

function showNotification(msg,type) {
    type = type?type:"ok";
	$('#notification').remove();
	$('body').append('<div id="notification" style="top:-26px" class="'+type+'">'+msg+'</div>');

	$('#notification').animate({
			top: '+=98'
		}, 500).delay(5000).fadeOut('slow');
}

function showStaticWarning(msg) {
	$('#notification').remove();
	$('body').append('<div id="notification" style="top:-26px" class="warning">'+msg+'</div>');

	$('#notification').animate({
			top: '+=98'
		}, 500)
}


function clearTabError() {
    $(".boxForTheError").hide()
}
function showTabErrors(div, title, msgs) {
    var s = "<ul>"
    for (var i = 0; i < msgs.length;i++) {
        s = s+"<li>"+msgs[i]+"</li>"
    }
    s = s + "</ul>"
    showTabError(div, title, s)

}
function showTabError(div, title, msg) {
	var errorString = "<div class='errorPanel rounded'><div class='arrow'>";
	errorString += "<h3>"+ title + "</h3>";
	errorString += "<div class='content'>" + msg + "</div>";
	errorString += "</div></div>";

    $(div).find(".boxForTheError").hide().html(errorString).fadeIn()
}

function fillUserDepartmentsSpan(span) {
    var checked = span.next('ul').find(':checked');

    var joinStr = checked.map(function() {
        return $(this).next("label").html()
    }).get().join(", ");

    span.html(joinStr);
}


function confirm(message, callback) {
	$('body').append("<div id='confirm'><div class='modalHeader'><h2>Confirm</h2></div><div class='content'><div class='message'></div><div class='actionPanel floatRight'><a class='button yes' href='javascript:void(0)'><span>Yes</span></a><a class='secondButton no cancelButton' href='javascript:void(0)'><span>No</span></a></div><div class='clearAll'></div></div>");
    var p =   $('#confirm');
	p.modal({
		minWidth: 350,
	/*	minHeight: 150,*/
		onShow: function (dialog) {
			$('.message', dialog.data[0]).append(message);

			// if the user clicks "yes"
			$('.yes', dialog.data[0]).click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
                p.remove();
			});
            // if the user clicks "no"
			$('.no', dialog.data[0]).click(function () {
				// close the dialog
				$.modal.close();
                p.remove();
			});
		}
	});
    p.parents('.simplemodal-container').height(p.find('.content').outerHeight());
}

function accordion() {

	$(".accordionPanel .accordionItem").each(function() {
		var $this = $(this);

		if (!$this.hasClass('active')) {
			$this.find('.content').hide();
		}
		
	});
	
	$(".simplemodal-container .helpPanel .greenList").each(function() {
        var $this = $(this);

		if (!$this.hasClass('active')) {
			$this.hide();
		}
	});	

}
function changeAccordion(e, activeId) {
	oldItem = e.parents('.accordionItem');
	wrapper = oldItem.parent('.accordionPanel');
	activeItem = wrapper.find(activeId);
	
	oldItem.removeClass('active')
		.find('.content').slideUp();
		
	activeItem.addClass('active')
		.find('.content').slideDown();

    $('#' + oldItem.attr('id') + 'Help').slideUp();
    $('#' + activeItem.attr('id') + 'Help').slideDown();
}

function setBusinessHourPanelInPhones() {
	$('input.hoursEnabled').each(function(){
		if($(this).is(':checked')) {
			$(this).parent('.enabledPanel').next('.enabledDetails').show();
		} else {
			$(this).parent('.enabledPanel').next('.enabledDetails').hide();
		}
	});

	$('input.hoursEnabled').live('click', function() {
		if($(this).is(':checked')) {
			$(this).parent('.enabledPanel').next('.enabledDetails').slideDown();
		} else {
			$(this).parent('.enabledPanel').next('.enabledDetails').slideUp();
		}
	});
}

function showRowDetails(wrap, row){

	r = $(row);
	// if already active do NOTHING
	if (!r.hasClass('active')) {
		hideRowDetails(wrap);
		r.addClass('active');

		if(isDirty){
           if (confirm('There are unsaved changes, do you want to continue?')) {
                isDirty = false
           }
        }
		// if form dosen't exist clone form
		nextRow = r.next('tr');

		nextRow.show();

	}

}

function hideRowDetails(wrap,type){

	if (type == "fade") {
		$(wrap).find('tbody').find('tr.active').removeClass('active').next('.edit_row').fadeOut();
	} else {
		$(wrap).find('tbody').find('tr.active').removeClass('active').next('.edit_row').hide();
	}
}

function cleanFakepath(v) {
    return v.replace("C:\\fakepath\\","")
}

function getPosInArray(description, tabs){
    var i = 0;
     for (i =0;i<tabs.length;i++){
       if (tabs[i] == description){
        return i;
       }
     }
    return 0;
}

var tabNames = {"connfu":  ['users', 'departments', 'ringonumbers', 'crm', 'settings'],
                "ringio":  ['users', 'departments', 'ringonumbers', 'crm', 'settings'],
                "inphonex": ['users', 'departments', 'ringonumbers', 'crm', 'devices', 'settings'],
                "vvs": ['users', 'departments', 'ringonumbers', 'settings']};

function getTabCount(brand){
    return tabNames[brand].length
}

function createTabsArrayByBrand(brand){
    return tabNames[brand]
}


