var cmPrevNext = {'id_content':0,'flow':[]};

// loads any cmContent_* div
var cmSetContent = function( prevNext ) {
    if (cmDebug) { alert('cmSetContent'); }
    jQueryCM("div[ id ^= 'cmContent_' ]").each(function(idx,item) {
        id_content = 0;
        next_page = 0;
        // id_content may be passed in for prev/next (which includes the id_content & page)
        if (prevNext == 'null') {
            // no id_content passed in... use the id_content from the content DIV
            id_content = jQueryCM(item).attr('data-id_content');
        } else {
            // id_content was passed in... use the id_content from the content DIV
            prevNext = prevNext.split('-');
            id_content = prevNext[0];
            next_page = prevNext[1];
        }
        
        // set the URL vars for readability
        section_complete = jQueryCM(item).attr('data-section_complete');
        section_viewed   = cmPrevNext['flow'].length > 0 ? cmPrevNext['flow'].join(',') : '0';
        
        // create the URL and call the ws 
        url = cmWebRoot+"/ws_content.php?id_partner="+jQueryCM(item).attr('data-id_partner')+"&id_content="+id_content+"&next_page="+next_page+"&id_content_alt="+jQueryCM(item).attr('data-id_content_alt')+"&section_complete="+section_complete+"&section_viewed="+section_viewed+"&cDiv="+item.id;
        if (cmDebug) { alert('About to call webservice: \n\n' + url); }
        jQueryCM.getJSON(url+"&callback=?", function(data){
            cmProcessContentJSON(data,item);
            return false;
        });
    });
}.defaults('null');

// reload any cmContent_* div since user has now logged in/out
function cmAltContent() {
    if (cmDebug) { alert('cmAltContent'); }
    jQueryCM("div[ id ^= 'cmContent_' ]").each(function(idx,item) {
        if (jQueryCM(item).attr('data-id_content_alt')) {
            var idc = jQueryCM(item).attr('data-id_content');
            jQueryCM(item).attr('data-id_content', jQueryCM(item).attr('data-id_content_alt'));
            jQueryCM(item).attr('data-id_content_alt', idc);
        }
    });
    cmSetContent();
}

// submits any cmContent_* div AND reloads it
function cmProcessContentJSON(data,item) {
    if (cmDebug) { alert('DEBUG (content): '+data['debug']); }

    var cDiv  = '#'+data['cDiv'];
    var cForm = '#cmContentForm_'+data['id_content'];

    // write the html
    if (data['html']) {
        jQueryCM(cDiv).html(data['html']);
        if (data['section_complete'])   { jQueryCM(cDiv).attr('data-section_complete', data['section_complete']); }
        if (data['id_content'])         { jQueryCM(cDiv).attr('data-id_content', data['id_content']); }
        if (data['id_content_alt'])     { jQueryCM(cDiv).attr('data-id_content_alt', data['id_content_alt']); }
    } else {
        jQueryCM(cDiv).html(data['error']);
    }

    // set the prev/next buttons
    cmSetPrevNext(data);

    // instantiate the validator
    jQueryCM(cForm).validate({
		errorContainer: "#messageBox",			  
		errorLabelContainer: "#errorBox",
   		wrapper: "li"
	});
	jQueryCM.extend(jQueryCM.validator.messages, {
        required: "You need to answer the question to continue"
    });

    // bind the form and provide a simple callback function 
    jQueryCM(cForm).ajaxForm({
        dataType:       'jsonp',
        success:        cmProcessContentJSON,
        beforeSubmit:   cmPreProcessRequest,
        type:           'get',
        url:            cmWebRoot+'/ws_content.php',
        clearForm:      true,
        timeout:        10000
    });
    
    // update/enable the 'account' page link
    if (cmPartnerAcctPage.length != 0) {
        cmAcctPage = cmPartnerAcctPage;
        if (lang == 'es' && cmPartnerAcctPageES.length != 0) {
            cmAcctPage = cmPartnerAcctPageES;
        }
        // build necessary params from the HTML attr (if any)
        cmAcctPage = cmAcctPage.match('/\?/') ? cmAcctPage : cmAcctPage+'?';
        cmAcctPage = cmAcctPage + (jQueryCM("#cmChartAcctURL").attr("data-utm_content") ? '&utm_content='+jQueryCM("#cmChartAcctURL").attr("data-utm_content") : '');
        cmAcctPage = cmAcctPage + (jQueryCM("#cmChartAcctURL").attr("data-utm_source") ? '&utm_source='+jQueryCM("#cmChartAcctURL").attr("data-utm_source") : '');
        jQueryCM("#cmChartAcctURL").attr("href", cmAcctPage);    // *_chart.tpl
        jQueryCM(".cmPartnerAcctPage").show();
    }
    // update/enable the 'home' page link
    if (cmPartnerHomePage.length != 0) {
        cmHomePage = cmPartnerHomePage;
        if (lang == 'es' && cmPartnerHomePageES.length != 0) {
            cmHomePage = cmPartnerHomePageES;
        }
        jQueryCM("#cmChartHomeURL").attr("href", cmHomePage);    // *_chart.tpl
        jQueryCM(".cmPartnerHomePage").css("display","block");
    }

    // NOTE: in addition to normal callbacks, we could name a uiOptions() callback and run that first
    // execute any callbacks
    jQueryCM.each(data['callback'], function (k,v) {
        if (cmDebug) { alert('CALLBACK: '+v); }
        eval(v);
    });
	
	// as long as the page has GA running, call a pageview
	// trackLoads is set in cmGlobal
	if(typeof(pageTracker) == 'object' && trackLoads){
		//TODO: pass partner/section/question
		pageTracker._trackPageview('cmcore/Q'+data['id_content']);
		if (cmDebug) { alert('Page tracked: Q'+data['id_content']); }
	}
}

function cmSetPrevNext( data ) {
    // set the current id_content
    idc_page = data['id_content']+'-'+data['page'];
    if (jQueryCM.inArray(idc_page,cmPrevNext['flow']) == -1) {
        cmPrevNext['flow'].push(idc_page);
    }

    // set "next" in the global var
    if (data['next_idc'] && data['next_page']) {
        next_idc_page = data['next_idc']+'-'+data['next_page'];
        if (jQueryCM.inArray(next_idc_page,cmPrevNext['flow']) == -1) {
            cmPrevNext['flow'].push(next_idc_page);
        }
    }

    // get the index of the current id_content-page
    idx_idc_page = jQueryCM.inArray(idc_page,cmPrevNext['flow']);

    // set "previous" button
    if (idx_idc_page > 0 || (data['display_type'] && data['display_type'] == 'landing_tmpl')) {
        idx_prev = data['display_type'] && data['display_type'] == 'landing_tmpl' ? idx_idc_page : idx_idc_page - 1;
        jQueryCM(".cmContentPrev").toggle();
        if (cmDebug) { jQueryCM(".cmContentPrev").attr('title',cmPrevNext['flow'][idx_prev]); }
        jQueryCM(".cmContentPrev").click(function() {
            cmSetContent( cmPrevNext['flow'][idx_prev] );
        });
    }
    
    // set "next" button
    if (cmPrevNext['flow'][idx_idc_page + 1]) {
        idx_next = idx_idc_page + 1;
        jQueryCM(".cmContentNext").toggle();
        if (cmDebug) { jQueryCM(".cmContentNext").attr('title',cmPrevNext['flow'][idx_next]); }
        jQueryCM(".cmContentNext").click(function() {
            cmSetContent( cmPrevNext['flow'][idx_next] );
        });
    }
}