selectedDivs = []; // keeps the divs which where opened with function toggleDiv
unselectedDivs = [];// keeps the divs which where closed with function toggleDiv
toggleDiv = function(divId) {
    var div = $('#' + divId);
    if(div.is(':hidden')) {
        div.slideDown('slow');
        if($.inArray(divId, selectedDivs) == -1) {
            selectedDivs.push(divId);
        }
        if($.inArray(divId, unselectedDivs) > -1) {
            unselectedDivs = $.grep(unselectedDivs, function (a) { return a != divId; });
        }
    } else {
        div.slideUp('slow');
        if($.inArray(divId, selectedDivs) > -1) {
            selectedDivs = $.grep(selectedDivs, function (a) { return a != divId; });
        }
        if($.inArray(divId, unselectedDivs) == -1) {
            unselectedDivs.push(divId);
        }
    }
}

loadCentralContent = function(fileName, title, subheading, magazineBaseUrl, articleUrl) {
    var picSrc = magazineBaseUrl + 'data/magazines/' + fileName;
//    $('#dynamic-central-picture').fadeOut('fast', function() {
        $('#dynamic-central-picture').attr({'src':picSrc});
        $('#dynamic-central-picture').attr({'alt':title})
//        if (this.complete) $(this).fadeIn('fast');
//    });
    $('#header').html(title);
    $('#content').html(subheading);
    $('#articleUrl').attr({'href':articleUrl});       
}

getMostRead = function(magazineBaseUrl) {
    $.ajax({
       url: magazineBaseUrl + 'index/mostread',
       type:'POST',
       dataType: 'json',
       success: function(data) {
           $('#tabContent').hide('fast');
           $('#tabContent').html(data.content);
           $('#tabContent').slideDown('slow');
           switchClassNames($('#most-read-tab-id'), 'inactive', 'active');
           switchClassNames($('#most-commented-tab-id'), 'active', 'inactive');
       }
    });
}

getMostCommented = function(magazineBaseUrl) {
    $.ajax({
       url: magazineBaseUrl + 'index/mostcommented',
       type: 'POST',
       dataType: 'json',
       success: function(data) {
           $('#tabContent').hide('fast');
           $('#tabContent').html(data.content);
           $('#tabContent').slideDown('slow');
           switchClassNames($('#most-read-tab-id'), 'active', 'inactive');
           switchClassNames($('#most-commented-tab-id'), 'inactive', 'active');
       }
    });
}

switchClassNames = function(el, oldClassName, newClassName) { 
    if(oldClassName != null) {
        if(oldClassName.constructor.name != 'Array') {
            el.removeClass(oldClassName);
        } else {
             for(var i = 0; i < oldClassName.length; i++)  {
                 el.removeClass(oldClassName[i]);
             }
        }
    }
    if(newClassName != null && !el.hasClass(newClassName)) {
        el.addClass(newClassName);
    }
}

showPageContent = function(el, articleId, no, magazineBaseUrl) {
    if(no == null) {
        $('#numbers').children('li').each(function(i) {
            if($(this).children('a').hasClass('active')) {
               no = i + 1;
               el = $(this).next().children('a');
           }
        });
    }
    window.location = magazineBaseUrl + 'article/view/id/' + articleId + "?page=" + (no + 1);
   /* $.ajax({
       url: magazineBaseUrl + 'article/getpage',
       type:'POST',
       data: {'page':no, 'id':articleId},
       dataType: 'json',
       success: function(data) {
            $('.active').removeClass('active');
            el.addClass('active');
            $('#article-content-div').html(data.content);
            if(data.fontSize > 0) {
                changeFontSize(data.fontSize, magazineBaseUrl);
            }
            if(data.isLast){
                $('#next-page').hide();
                if(no > 1) { // means it has more than 1 pages as last page is not page number 1
                    $('#articleInterestedArea').hide();
                    $('#commentsOnArticle').show();
                }
            } else {
                $('#next-page').show();
                $('#articleInterestedArea').show();
                $('#commentsOnArticle').hide();
            }
       }
    });        */
}

expandSelectedArticles = function(selDivs) {
   if(selDivs != "null") {
        var divs = eval('(' + selDivs + ')');
        $.each(divs, function(n){
           $(divs[n]).show();
       });
   } 
}

goToArticlePage = function(articleId, thisDiv, magazineBaseUrl) {
   // check if the current div of the article being clicked is already in selectedDivs array
    if($.inArray(thisDiv, selectedDivs) == -1) {
        selectedDivs.push(thisDiv);
    }

    $.ajax({
       url: magazineBaseUrl + 'article/getselecteddivs',
       data: {'selectedDivs':selectedDivs.join(','), 'unselectedDivs' :  unselectedDivs.join(','),'id':articleId},
       dataType:'json',
       type: 'POST',
       success: function(data) {
           window.location.href = magazineBaseUrl + data.articlePartialPath + data.id;
       }
    });
}

changeFontSize = function(size, url) {
    
    $(".size1Active").removeClass("size1Active");
    $(".size2Active").removeClass("size2Active");
    $(".size3Active").removeClass("size3Active");
    
    $("#size_"+size).addClass("size"+size+"Active");
    
    // get the normal size for the first paragraph
    $.ajax({
    	url: url + 'article/getsessionvars',
        type:'POST',
        dataType:'json',
        data:{'newSize':size},
        success: function(data) {
            var newFontSize = data['newSizeValue'];
            $('#article-content-div p').each(function(n){
                var hasSpans = $(this).find('span').length;
              //  if(hasSpans == 0) {
                    $(this).css('font-size', newFontSize);
          //      }
            });
            $('#article-content-div span').each(function(n){
                $(this).css('font-size', newFontSize);
            });
        } // END IF SUCCESS
    });
}

getCurrentFontSize = function(url) {
    $.ajax({
       url : url + 'article/getcurrentfontsize',
       dataType: 'json',
       type:'POST',
       success: function(data) {
           if(data['currentSize'] != 0) {
               changeFontSize(data['currentSize'], url);
           }
       }
    });
}

function showLoginWnd()
{
    $.modal('<div class="modalWindow" id="modal1"><div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center"><h1 class="boxTitle">Login Information</h1><br/>Please use the fields at the top of the page to login.<br/><br/><div style="text-align:right"><br/><img src="'+siteUrl+'magazine/images/btnClose.png" onclick="$.modal.close();"  style="cursor:pointer" id="calItemCloseBtn" /></div></div></div></div><div class="mbottom"></div></div>');
}

function call_ajax(redirectUrl){
    $.post(
            siteUrl+"login/index/get-user",
            {
                    user        : $('#email').val()
            }, 
            function(data)
            {
                
            }, 
            "html");
    $.post(
            siteUrl+"login/index/login",
            {
                email       : $('#email').val(),
                password    : $('#password').val()
            }, 
            function(data)
            {
                //alert(data);
                if (data.login == true){
                    isLogged = 1;
                    $.modal.close();
                    $('div#topHeader').html('<div id="logout"><a href="'+siteUrl+'/my-cues">My CUES</a> | <a href="#">Profile</a> | <a href="'+siteUrl+'/logout">Logout</a></div>');
                
                    //alert('submit login form ...');
                    
                    if(redirectUrl != '' && redirectUrl != null && redirectUrl != undefined){
                        //window.location.replace(redirectUrl);
                        window.location.href = redirectUrl;
                    }
                    
                    if (redirectUrl.substr(-13) == '/fullReport/1'){
                        $('#fileType').val('full');
                        $('#downloadForm').submit();
                    }
                }
                else{
                    alert('Login failed!');
                }
            }, 
            "json");
    
    /* var url = "<?php echo Zend_Registry::get('config1')->site->mag_url; ?>login/index/login/us/" + $('#email').val();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "html"
        }); */
            
}

 
function modalLogin(options){
    var chosen_message='';
    //default_message = 'Our membership services team can help you out right away, just click to chat.';  
    default_message = 'Please join as a <a href="'+siteUrl+'mycues/signup/executive/">CUES Member</a> or <a href="'+siteUrl+'mycues/signup/director/">CUES Director Member</a> to review the Full Report.';  
    
    if (typeof(options.message) == 'undefined') {
        chosen_message += default_message;
    } else{                  
        chosen_message += options.message;
    }                                      
    $.modal('<div class="modalWindow" id="modal1">'+
            '<div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center">'+
            
            '<div style="float:right; margin-top:-10px;"><img src="'+siteUrl+'images/controls/modalClose.png" onClick="$.modal.close();" class="action"></div>'+
            
            '<h1 class="boxTitle">Please login first</h1><form name="login_form" method="post" onSubmit="return false;">'+
            '<table><tr><td style="padding-left:15px;" align="right">Username:</td><td align="left">'+
            '<input class="inputText" type="text" name="email" id="email" /></td></tr><tr><td style="padding-left:15px;" align="right">Password:</td><td align="left">'+
            '<input class="inputText" type="password" name="password" id="password" /></td></tr>'+
            '<tr><td colspan="2" align="right">'+
            '<a href="'+siteUrl+'shop-cues/membership"><img src="'+siteUrl+'images/mycues/default/layouts/main/btnJoin.png" alt="Join now!"/></a> '+
            '<input onclick="call_ajax(\''+  options.redirectUrl +'\');" class="btnInput" type="image" src="'+siteUrl+'images/mycues/default/layouts/main/login_btn.jpg"></td>'+
            '</tr></table></form>'+
            '<hr class="dottedHR" /><a href="#">Forgot your username or password?</a>'+
            '<br/><br/>'+chosen_message+'</div></div></div><div class="mbottom"></div></div>');  
}

function modalMessage(message, title, refreshPage){
	if(title == undefined){
		title = '';
	}
    
    if (typeof(refreshPage) != 'undefined')
    {
        $.modal('<div class="modalWindow" id="modal1"><div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center"><h1 class="boxTitle">'+ title +'</h1><br/><h4>'+ message +'</h4><br/><input onclick="$.modal.close(); location.reload();" class="btnInput" type="image" src="'+siteUrl+'images/mycues/default/layouts/main/cancel_btn.jpg"></div></div></div><div class="mbottom"></div></div>');
    }
    else
    {
        $.modal('<div class="modalWindow" id="modal1"><div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center"><h1 class="boxTitle">'+ title +'</h1><br/><h4>'+ message +'</h4><br/><input onclick="$.modal.close();" class="btnInput" type="image" src="'+siteUrl+'images/mycues/default/layouts/main/cancel_btn.jpg"></div></div></div><div class="mbottom"></div></div>');
    }
}

function postAjax(url, modalMsg, formId){
    
    $.ajax(
    {
        type: "POST",
        url: url,
        data: $('#'+formId).serialize(),     
        success: function(msg)
        {
            if(modalMsg !== true)
            {
                $('#'+formId).html(msg);
            } 
            else 
            {
                $.modal.close();
                modalMessage(msg);
            }
        }
    });
}

function modalFormOld(title,url,options,beforeForm, afterForm, buttons, modalMsg){
        var postData;
        var html = '<div class="modalWindow" id="modal1"><div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center"><h1 class="boxTitle">'+title+'</h1>'+ ((beforeForm != undefined && beforeForm != null) ? beforeForm : '') +'<form id="frm12345" method="post" onSubmit="return false;"><table>';
        $.each(options, function(){
            html+= '<td style="padding-left:15px;" align="right">'+this.label+': </td><td align="left" class="modalFormInput"><' + (this.type == 'text' ? 'input' : ( this.type == 'textarea' ? 'textarea' : 'input' )) + ' '+(this.value != undefined ? 'value="'+this.value+'" ':'""')+' class="txtInput" ' +( this.type != 'textarea' ? 'type="'+this.type+'"' : '' )+ ' name="'+this.name+'" id="'+this.name+'" '+ ( this.type != 'textarea' ? '/>' : '></textarea>' ) +' </td></tr>';
        });
        html+= '<tr><td colspan="2" align="right"><input onclick="$.modal.close();" class="btnInput" type="image" src="' +((buttons == undefined || buttons.cancel == undefined) ? siteUrl+'images/mycues/default/layouts/main/cancel_btn.jpg' : buttons.cancel )+ '">&nbsp;<input onclick="postAjax(\''+url+'\', true);" class="btnInput" type="image" src="' +((buttons == undefined || buttons.go == undefined) ? siteUrl+'images/mycues/default/layouts/main/login_btn.jpg' : buttons.go )+ '"></td></tr>';
        html += '</table></form><hr class="dottedHR" /><br/>'+ ((afterForm != undefined && afterForm != null) ? afterForm : '') +'</div></div></div><div class="mbottom"></div></div>';
        $.modal(html);
}

function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}


function modalForm(formIdKey, title,url,options,beforeForm, afterForm, buttons, modalMsg){
        var postData;
        var formId = "modalForm" + formIdKey;
        // so that we can use multiple forms on one page
        var html = '<div class="modalWindow" id="modal1"><div class="mtop"></div><div class="mmain"><div class="mcenter"><div class="center"><h1 class="boxTitle">'+title+'</h1>'+ ((beforeForm != undefined && beforeForm != null) ? beforeForm : '');
        html += '<form id="'+formId+'" method="post" onSubmit="return false;" style="text-align:center">';
        $.each(options, function(){
            if (this.type == "hidden")
            html+= '<input type="hidden" id="'+this.name+'" name="'+this.name+'" value="'+this.value+'"/>';
        });

        html += '<table style="margin: auto;text-align:left"">';                    
        $.each(options, function(){
            if (this.type != "hidden")
                html+= '<td><label for="'+this.name+'">'+this.label+'</label><br/><' + (this.type == 'text' ? 'input' : ( this.type == 'textarea' ? 'textarea' : 'input' )) + ' '+(this.value != undefined ? 'value="'+this.value+'" ':'""')+' class="'+this.classValidation+'" ' +( this.type != 'textarea' ? 'type="'+this.type+'"' : '' )+ ' name="'+this.name+'" id="'+this.name+'" '+ ( this.type != 'textarea' ? '/>' : '></textarea>' ) +' </td></tr>';
        });
        html+= '<tr><td align="center"><input onclick="$.modal.close();" class="btnInput" type="image" src="' +((buttons == undefined || buttons.cancel == undefined) ? siteUrl+'images/controls/btnClose.png' : buttons.cancel )+ '">&nbsp;<input onclick="submitModalForm(\''+url+'\', true, \''+formId+'\');" class="btnInput" type="image" src="' +((buttons == undefined || buttons.go == undefined) ? siteUrl+'images/controls/btnSend.png' : buttons.go )+ '"></td></tr>';
        html += '</table></form>'+ ((afterForm != undefined && afterForm != null) ? afterForm : '') +'</div></div></div><div class="mbottom"></div></div>';
        $.modal(html);
        
        window.scrollTo($('#modal1').offset().left, $('#modal1').offset().top);
        
        //$.scrollTo( $('#modal1'), { duration: 500, axis: 'xy' } ); 

        
        var validator = $("#" + formId).validate({meta: "validate"});
}

function submitModalForm(url, modalMsg, formId)
{
    //alert($("#" + formId).valid());
    if ( $("#" + formId).valid() == true ) 
        postAjax(url, modalMsg, formId);   
}
function requestBrochure(file){
    modalForm(
        'requestBrochure',
        'Request a Brochure',
        siteUrl + "request-brochure/request-brochure",
        [
            {
                name:'name',
                label:"<span class='registerRequired'>*</span>Name", 
                type:'text',
                classValidation:"inputText {validate:{required:true, messages:{required:' *'}}}"  
            },{
                name:"email",
                label:"<span class='registerRequired'>*</span>E-mail Address",
                type:"text",
                classValidation:"inputText {validate:{required:true, email:true, messages:{required:' *', email:' *'}}}"
            },
            {
                name:"fileName",
                type:"hidden",
                value:file
            }
        ],
        '',
        '<a href="'+siteUrl+'data/brochures/'+ file +'" id="brochure_download_link">Download Brochure Now</a>'
    );
}

function loadFileFeature(feature){
    
    $.ajax({
        url: siteUrl + "request-brochure/file-feature/ff/" + feature,
        dataType: 'json',
        success: function(data){
            //console.log(data);
            modalForm(
                'fileFeature',
                data.feature.popup_title,
                siteUrl + "request-brochure/file-feature-email",
                [
                    {
                        name:'name',
                        label:"<span class='registerRequired'>*</span>Name", 
                        type:'text',
                        classValidation:"inputText {validate:{required:true, messages:{required:' *'}}}"  
                    },{
                        name:"email",
                        label:"<span class='registerRequired'>*</span>E-mail Address",
                        type:"text",
                        classValidation:"inputText {validate:{required:true, email:true, messages:{required:' *', email:' *'}}}"
                    },
                    {
                        name:"fileName",
                        type:"hidden",
                        value:data.feature.file_to_send
                    },
                    {
                        name:"ffId",
                        type:"hidden",
                        value:data.feature.id
                    }
                ],
                '',
                '<a href="'+siteUrl+'data/file-feature/'+ data.feature.file_to_send +'" id="ff_download_link">'+ data.feature.popup_copy +'</a>'
            );       
        }
    });
    
}

$(document).ready(function () {
    $('#modalFormfileFeature input').live('keypress',function(e){
        
        if(e.which == 13 || e.which == 10){
            //$('form#login').submit();
            
            submitModalForm(siteUrl + 'request-brochure/file-feature-email', true, 'modalFormfileFeature');
               
            e.preventDefault();
            return false; 
        }
    });
    
    $('#modalFormrequestBrochure input').live('keypress',function(e){
        
        if(e.which == 13){
            //$('form#login').submit();
            
            submitModalForm(siteUrl + 'request-brochure/request-brochure', true, 'modalFormrequestBrochure');
               
            e.preventDefault();
            return false; 
        }
    });
});

