var arr = window.location.pathname.split('/');
var url_action = arr[arr.length-1];
var newId ;
var view = 1;
function switchCalendarView(link, v){
		
        //old view
        $('#viewType' + view).removeClass('calViewTypeSelected');
        $('#viewType' + view).addClass('calViewType');
        //new view
        newId = $(link).attr('id').substr(8);
        //console.log(newId);
        $('#viewType' + newId).addClass('calViewTypeSelected');
        view = newId;
    }
	
    

$(document).ready(function(){ 
    $('#mycues_edit_feeds').click(function(){
        window.location.href = siteUrl + "Feeds";
    });
    
    $('#become_member').mouseover(function(){
        $(this).addClass('cursor-link-cls');
    });
    
    $('#become_member').click(function(){
        //window.location.href = siteUrl + 'mycues/signup/executive';
        window.location.href = siteUrl + 'signup/index/executive';
    });
    
    if (url_action == 'feeds' || url_action == 'Feeds'){
       
        $("#feed_what_is").tooltip({
            fixPNG: true,
            bodyHandler: function() { 
                    return "Really Simply Syndication (RSS)<br />makes it easy to track news updates,<br />blogs, audio and video posts.";
            }
        });
    }
    
    //$('.tooltip_link').tooltip({fixPNG: true});
    
    
    /*$('#feed_what_is').click(function(){
        window.open(siteUrl + 'feeds/what-is');
    });*/
    
    //calendar views
	
	
    $('#viewSelector a').click(function(){
		switchCalendarView(this);
	});
    
    //chat link
    $('#liveChatLink br').remove();
    
	//document links tracking
	$("a[href$=pdf], a[href$=doc], a[href$=docx], a[href$=xls]").each(function(){
		
		$(this).click(function(){
			
			var path = $(this).attr('href').split('/');
			pageTracker._trackEvent('Documents', 'Downloaded', path[path.length-1]);
			
		});
	});
});

function trackSendToAFriend()
{
	pageTracker._trackEvent('Emails', 'Sent', window.location.href);
	window.location.href;
}


function submitSurvey(baseUrl){
	var options_list = '';
	if ($('#box_type').val() == 1){ //radio buttons
		$("input[name='radio_']:checked").each(function() {
		    options_list = $(this).val();
		});
	}
	else{ //checkboxes
		var options  = new Array();
		$("input[name='check[]']:checked").each(function() {
		    options.push($(this).val());
		});
		options_list = options.join(',') 
	}
	
	if (options_list == ''){
		alert('Please select an option!');
	}
	else{
		$.post(
				baseUrl+"default/my-cues/vote",
				{
	       		 	survey_id	: $('#question_id').val(),
	       		 	answer		: options_list
	        	}, 
	        	function(data)
	        	{
	        		$('#submit_image').remove();
	        		$('#vote_message').append(data);
	        	}, 
	        	"html");
	}
}

function showSurveyGraphic(baseUrl, id, legend, question){
	$('#survey-modal-content').modal();

	$.get(
        baseUrl+"default/my-cues/get-chart-values", 
        {
            'survey_id' :id 
        }, 
        function(data){
		    var myvalues = data.split(',');
		    var mycolors = ['#CC66FF', '#6699FF', '#99CC99', '#ff9933', '#FFFF99'];
		    var total = 0;
            
		    for (i=0; i<myvalues.length; i++){
			    total += parseInt(myvalues[i]);
		    }
		    
		    /* Sparklines can also take their values from the first argument  passed to the sparkline() function */
            $('.dynamicbar').sparkline(myvalues, {type: 'pie', height: 200, width: 200, sliceColors :mycolors, offset:'+90'} );
            
            legend_arr = legend.split('{|}');
            complete_legend = '';
            for(i=0; i<legend_arr.length; i++){
        	    complete_legend += '<div class="legend_entry">'+
        						    '<span style="width:3px; height:3px; background-color:'+mycolors[i]+'">&nbsp&nbsp&nbsp&nbsp</span> '+
        							    (legend_arr[i])+' ['+((myvalues[i]/total)*100).toFixed(2)+' %]'+
        						    '</div>';
            }
            
            $('#chart_legend').html(complete_legend);
            $('#question_title').html(question);
	});	
}


function addRssFeed(baseUrl){
	$('#feed-modal-content').modal();
	
	$('#add_private_feed').click(function(){
		if (!$('#rss_title').val()){
			alert('Please provide RSS Title.');
		}
		else {
			if (!$('#rss_feed').val()){
				alert('Please provide RSS Feed.');
			}
			else{
				
				$.post(
						baseUrl+"default/feeds/add-private-feeds",
						{
			       		 	rss_title	: $('#rss_title').val(),
			       		 	rss_feed	: $('#rss_feed').val()
			        	}, 
			        	function(data)
			        	{
			        		new_feed = '<input type="checkbox" name="private[]" value="'+data+'" checked="checked">'+ $('#rss_title').val()+'<br />';
							$('#personal_feeds').append(new_feed);
							$.modal.close();
			        	}, 
			        	"html");
			}
		}
	})
}


function markFeedArticleAsRead(baseUrl, feed_id, article_id, user_id){
	$.post(
			baseUrl+"default/my-cues/mark-read-article",
			{
       		 	feed_id		: feed_id,
       		 	article_id	: article_id,
       		 	user_id		: user_id
        	}, 
        	function(data)
        	{
        		$('#feed_article_'+article_id).removeClass('unread_article');
        		$('#feed_article_'+article_id).addClass('read_article');
        	}, 
        	"html");
}

function gotoArticle(article_url){
	//$("a").attr('href',article_url);
	//$("a").attr('target','_blank');
}
oldSortCriteria = 'startDate';
function sortEvents(criteria, page){
	criteria == null ? globalSortCriteria = 'startDate' : globalSortCriteria = criteria;
	
	$('#'+ oldSortCriteria + '_sort').removeAttr('class');
	if(globalSortDirection == 'ASC'){
		globalSortDirection = 'DESC';
		$('#'+ globalSortCriteria + '_sort').removeClass('sortASC');
		$('#'+ globalSortCriteria + '_sort').addClass('sort' + globalSortDirection);
	} else {
		globalSortDirection = 'ASC';
		$('#'+ globalSortCriteria + '_sort').removeClass('sortDESC');
		$('#'+ globalSortCriteria + '_sort').addClass('sort' + globalSortDirection);
	}
	oldSortCriteria = globalSortCriteria;
	if(page == 'map'){
		councilRegionInfo(globalRegion, globalSortCriteria, globalSortDirection);
	}
	if(page == 'list'){
		getEventList(globalDate, globalTarget, globalKeyword, globalSortCriteria, globalSortDirection)
	}
	
}

function showEventInfo(eventId)
{
	$.getJSON(siteUrl + "calendar/index/get-event-info/id/" + eventId,
        function(data){
			if(data.thumb == null){
				$('.eventThumb img').attr('src', siteUrl + 'images/mycues/default/layouts/main/shop_image_default.jpg');
			} else {
				$('.eventThumb img').attr('src', siteUrl + 'images/events/' + data.thumb);
			}
			$('.eventInfo h1.boxTitle').html(notUndefined(data.title));
			$('.eventInfo .eventDate').html(notUndefined(data.startDate) + ' - ' + notUndefined(data.endDate));
			$('.eventInfo .eventLocation').html(notUndefined(data.location) + ', ' + notUndefined(data.city) + '<br/>' + notUndefined(data.address1) + '<br/>' + notUndefined(data.address2));
			$('#eventDescription').html(notUndefined(data.shortDescription));
			
			if(data.type == 3){
				$('#calItemInfoBtn').hide();
			}
			
			$('#calItemInfoBtn').click(function(){
				if(data.type == 1){
					window.location.href = siteUrl + 'dispatch/index/type/landing/id/' + data.eventId;
				}
				if(data.type == 2){
					window.location.href = siteUrl + 'dispatch/index/type/page/id/' + data.pageId;
				}
			});
        });
	
	$("#modal1").modal();
	$('#calItemCloseBtn').click(function(){
		$.modal.close();
	});
}

function notUndefined(item){
	if (item !== undefined) return item;
	else return '';
}

function displayMemberInfo(type, siteUrl)
{
    $.getJSON(siteUrl + "shopping-cart/checkout/membership-info?address="+$("input[id='addressId']:checked").val(),
        function(data)
        {
          if ( data.status == "OK" )
            {
                if (type=="billing")
                {
                    $('#billingAddressId').val(data.id);
                    $('#txtBillingAddress').val(data.street1);
                    $('#txtBillingAddress2').val(data.street2);
                    $('#txtBillingCity').val(data.city);
                    $('#lstBillingState').val(data.stateCode);
                    $('#txtBillingZip').val(data.zipCode);
                    $('#lstBillingCountry').val(data.country);
                    $('#txtBillingDayPhone').val(data.dayPhone);
                    $('#txtBillingEmail').val(data.email);
                }
                else
                {
                    $('#shippingAddressId').val(data.id);
                    $('#txtShippingFirstName').val(data.firstName);
                    $('#txtShippingLastName').val(data.lastName);
                    $('#txtShippingAddress').val(data.street1);
                    $('#txtShippingAddress2').val(data.street2);
                    $('#txtShippingCity').val(data.city);
                    $('#lstShippingState').val(data.stateCode);
                    $('#txtShippingZip').val(data.zipCode);
                    $('#lstShippingCountry').val(data.country);
                }
                $.modal.close()
            }
        });
}

function openCenteredWindow(url, title, width, height) 
{
     var left = parseInt((screen.availWidth / 2) - (width / 2));
     var top = parseInt((screen.availHeight / 2) - (height / 2));
     var windowFeatures = "width=" + width + ",height=" + height + ",status,scrollbars=yes,resizable=0,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
     myWindow = window.open(url, title, windowFeatures);
}

function openFormWnd(formId)
{  
        $.ajax({
        url: siteUrl + "dynamic-form/get-form-content",
        data: {
            formId  : formId
            },
        type: 'post',
        dataType: 'html',
        success: function (data) 
        {
                $('#dynamicFormCtrlContent').html(data);
                $("#dynamicFormCtrl").modal();        
        }
    });
}

function sendFormInfo()
{
    if ( $('#dynamicForm').valid() == true )     
        $.ajax(
        {
            type: "POST",
             url: siteUrl + "dynamic-form/send-form-content",
            data: $('#dynamicForm').serialize(),     
            success: function(msg)
            {
                info = parseServerJSON(msg);
                $.modal.close();
                               
                if (info.success == false)  modalMessage("The form could not be sent. Please try again", 'Error');
                else modalMessage(info.message, 'Success');                 
            }
        });
}

function sendNextGenFormInfo(successUrl, errorUrl)
{
    if ( $('#dynamicForm').valid() == true )   
    {  
        $("#btnSubmitNextGen").hide();
        $("#btnSubmitNextGen_loader").show();
        $.ajax(
        {
            type: "POST",
             url: siteUrl + "dynamic-form/send-form-content",
            data: $('#dynamicForm').serialize(),     
            success: function(msg)
            {
                info = parseServerJSON(msg);
                $.modal.close();
                
                if (info.success == false) $(location).attr('href',errorUrl);
                else $(location).attr('href',successUrl);   
                
                $("#btnSubmitNextGen").show();
                $("#btnSubmitNextGen_loader").hide();
            }
        });
    }
}

function getSslStateList(countryCtrlId, stateCtrlId, siteUrl, handlerMethod)
{
    country = $("#"+countryCtrlId).val();
    $.ajax(
        {
            type: 'post',
            url: siteUrl + "country-state/get-states",
            data: { country  : country },
            success: function(msg)
            {
                info = parseServerJSON(msg);
                $("#"+stateCtrlId+" options").remove(); 
                var options = "<option value=''>Please Select</option>";
                for(i = 0; i < info.length; i++)
                    options += "<option value='"+info[i].stateCode+"'>"+info[i].state+"</option>";
                $("#"+stateCtrlId).html(options);
                if ( $.isFunction(handlerMethod) ) handlerMethod();
            }
        });   
}

function getStateList(countryCtrlId, stateCtrlId, handlerMethod)
{
    country = $("#"+countryCtrlId).val();
    $.ajax(
        {
            type: 'post',
            url: siteUrl + "country-state/get-states",
            data: { country  : country },
            success: function(msg)
            {
                info = parseServerJSON(msg);
                $("#"+stateCtrlId+" options").remove(); 
                var options = "<option value=''>Please Select</option>";
                for(i = 0; i < info.length; i++)
                    options += "<option value='"+info[i].stateCode+"'>"+info[i].state+"</option>";
                $("#"+stateCtrlId).html(options);
                if ( $.isFunction(handlerMethod) ) handlerMethod();
            }
        });   
}

function getSslStateList(countryCtrlId, stateCtrlId, siteUrl, handlerMethod)
{
    country = $("#"+countryCtrlId).val();
    $.ajax(
        {
            type: 'post',
            url: siteUrl + "country-state/get-states",
            data: { country  : country },
            success: function(msg)
            {
                info = parseServerJSON(msg);
                $("#"+stateCtrlId+" options").remove(); 
                var options = "<option value=''>Please Select</option>";
                for(i = 0; i < info.length; i++)
                    options += "<option value='"+info[i].stateCode+"'>"+info[i].state+"</option>";
                $("#"+stateCtrlId).html(options);
                if ( $.isFunction(handlerMethod) ) handlerMethod();
            }
        });   
}

function openPrintVersion(){
   window.open(window.location.href + '?print=1', "mywindow", 'width=560, height=600, menubar=yes, scrollbars=yes, resizable=yes');
}

function loginUser(loginUrl, forumLoginUrl, redirectUrl, pUsername, pPassword, rememberMe)
{
    $("#btnLogin").hide();
    $("#loginLoader").show();
    $.post(
            loginUrl,
            {
                email       : pUsername,
                password    : pPassword,
                rememberMe  : rememberMe
            }, 
            function(data)
            {
                data = eval( '(' + data + ')' );
                if(data.login){
                    var url = redirectUrl; 
                    $.post(
                        forumLoginUrl,
                        {
                            username    : data.AccountID,
                            password    : pPassword,
                            rememberMe  : rememberMe
                        },
                        function(data)
                        {
                            $(location).attr('href',redirectUrl);
                        }
                    );
                } else {
                    $('#loginError').fadeIn('slow');
                    $("#btnLogin").show();
                    $("#loginLoader").hide();
                }
            }
            ,
            "html");
}

function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}
