
function call_api (obj) {
    
    api_returns($('#apiMETHOD').val(), $('#apiJSON').val());
    
}


function getFilters (obj) {
    
    json = null;
    o = $('#qtFilterSelect1').val();
    t = $('#qtFilterSelect2').val();
    s = $('#search_input').val();
    
    oj = false;
    si = false;
    
    if (s && (s != 'Search here...')) {
        si = '"search":"'+s+'"';
    }
    
    if ($('#f1-'+o).val()) {
        oj = '"'+o+'":"'+$('#f1-'+o).val()+'"';
    }

    showmine = '"showmine":"' + $('#showmine').val() + '"';
    

    if (oj) {
        if (si) {
            json = '{"filter":{'+oj+','+si+','+showmine+'}}';
        } else {
            json = '{"filter":{'+oj+','+showmine+'}}';    
        }
    } else if (si) {
        json = '{"filter":{'+si+','+showmine+'}}';    
    } else  {
        json = '{"filter":{'+showmine+'}}';    
    }
    
    api_returns('filters', json, obj);

    
    if (o) {
        /*
        oj='';
        if ($('#f1-'+o).val()) {
            oj = '"'+o+'":"'+$('#f1-'+o).val()+'"';
            if (obj == 3) {
                if ($('#f2-'+t).val()) {
                    oj += ',"'+t+'":"'+$('#f2-'+t).val()+'"';
                }
            }
            
        }

        cnt = ($('#resultCount').val());
        if (si) {
            if (oj) {
                json = '{"filter":{'+oj+','+si+','+showmine+'},"limit":"'+cnt+'"}';
            } else {
                json = '{"filter":{'+si+','+showmine+'},"limit":"'+cnt+'"}';
            }
        } else {
            if (oj) {
                json = '{"filter":{'+oj+','+showmine+'},"limit":"'+cnt+'"}';
            } else {
                json = '{"filter":{'+showmine+'},"limit":"'+cnt+'"}';
            }
        }
        */
        refreshCues(obj,0);
        //api_returns('cues', json);
    }
    
}

function api_returns (method, json, obj) {
    
    showMainLoader();
    $.getJSON("/qt/api.php?method=" + method + "&json=" + escape(json), function(data){
            
        switch(method)
        {
            case 'info':
                refreshInfo (data);
                break;
            
            case 'outputs':
                refreshOutputs (data);
                break;
            case 'filters':
                refreshFilters (data, obj);
                break;
            case 'cues':
                $('#apireturns').html('');                
                $('#cueList').html('');
                
                refreshCueList(data);
                    
                break;
            case 'arrangements':
                refreshArrangements (data);
                break;
            case 'build':
                processBuild (data, obj);
                break;
            default:
                $('#apireturns').html(method + ": " + data);
                break;
        }
                
        clearMainLoader();
            
    });
    
}

function refreshCues (obj, page) {
    
    oj='';
    if ($('#f1-'+o).val()) {
        oj = '"'+o+'":"'+$('#f1-'+o).val()+'"';
        if (obj == 3) {
            if ($('#f2-'+t).val()) {
                oj += ',"'+t+'":"'+$('#f2-'+t).val()+'"';
            }
        }
        
    }

    
    limit = $('#resultCount').val();
    
    if (!page) {
        page = 0;
    }
    
    if (si) {
        if (oj) {
            json = '{"filter":{'+oj+','+si+','+showmine+'},"page":"'+page+'","limit":"'+limit+'"}';
        } else {
            json = '{"filter":{'+si+','+showmine+'},"page":"'+page+'","limit":"'+limit+'"}';
        }
    } else {
        if (oj) {
            json = '{"filter":{'+oj+','+showmine+'},"page":"'+page+'","limit":"'+limit+'"}';
        } else {
            json = '{"filter":{'+showmine+'},"page":"'+page+'","limit":"'+limit+'"}';
        }
    }
    
    api_returns('cues', json);
}

function getOutputs() {
    api_returns ('outputs');
}

function refreshOutputs (data) {
    $('#typeFile').html('');
    o = '';
    if (data) {
        $.each(data, function(k, v) {
            if(v.name == 'final') {
                o += '<optgroup label="'+v.name+'">';
                if(v.outputSettings) {
                    $.each(v.outputSettings, function(kk, vv) {
                        if(vv.format) {
                            o += '<option>'+vv.format+'</option>';
                        }
                    });
                }
                
                o += '</optgroup>';
            }
        });
    $('#typeFile').append(o);
    }
}

function refreshCueList (data) {
    
    $('#pagination').html('');
    if (data) {
    if (data.cues.totalCount) {
        $('#resultTotal').html(data.cues.totalCount);
        if (data.cues.cues) {
            pFirst = '';
            pLast = '';
            pMid = '';
            page = 0;
            limit = $('#resultCount').val();
            
            if (parseInt(data.cues.totalCount) > parseInt(limit)) {
                
                lastpage = Math.ceil(data.cues.totalCount/limit)-1;
                if (data.cues.page) {
                    page = parseInt(data.cues.page);
                }
                pFirst = '<div class="pageFirst"><a href="javascript:refreshCues(3,0);">&laquo; FIRST</a></div>';
                pLast = '<div class="pageLast"><a href="javascript:refreshCues(3,'+lastpage+');">LAST &raquo;</a></div>';

                startpage = Math.max(0, page-4);
                endpage = Math.min(lastpage-1, startpage+7);
                if (endpage>7) {
                    startpage = endpage-7;
                }
                
                for (x = startpage; x < endpage; x++) {
                    
                    if (page == (x + 1)) {
                        cls = 'pageActive';
                    } else {
                        cls =  'page';
                    }

                    pMid += '<div class="' + cls + '"><a href="javascript:refreshCues(3,'+(x+1)+');">' + (x + 2) + '</a></div>';
                }
    
            }
            
            $('#pagination').html(pFirst + pMid + pLast);
            
            $.each(data.cues.cues, function(k, v) {
                if(v.cueName) {
                    cueRec = '<div class="trackInfo" id="track' + v.cueID + '">';
                    cueRec += '<div class="tiOne">';
                    if (v.cueIsMLM == 1) {
                        cueRec += '  <img src="/qt/images/mlIcon.png" alt="Multi-Layer track" /><br />';
                    } else {
                        cueRec += '  <img src="/qt/images/SLIcon.png" alt="Single-Layer track" /><br />';
                    }
                
                    //cueRec += '  <a href=""><img src="/qt/images/info.png" alt="Track Info" /></a>';
                    cueRec += '</div>';
                
                    
                    cueRec += '<div class="tiTwo">' +
                    '  <div class="twoTitle">' +
                    '      <ul>' +
                    '          <li class="trackTitle">'+ v.cueName + '</li>' +
                    '          <li class="albumTitle">' + v.albumName + '</li>' +
                    '          <li class="tempo">' + v.cueTempo + '</li>' +
                    '          <li class="intensity">';
                
                    if (v.cueIntensity <= 429 ) {
                        cueRec += '+';
                    } else if (v.cueIntensity <=599 ) {
                        cueRec += '++';
                    } else if (v.cueIntensity <=674 ) {
                        cueRec += '+++';
                    } else if (v.cueIntensity <=749 ) {
                        cueRec += '++++';
                    } else if (v.cueIntensity <=1000 ) {
                        cueRec += '+++++';
                    }
                            
                    cueRec += '</li>' +
                    '      </ul>' +
                    '  </div>';
                    
                    cueRec += '<div class="descr">';
                    cueRec +=   '      <p>' ;
                    if (v.cueDescription) {
                        cueRec += v.cueDescription.substr(0, 380)  + '<br />';
                    }
                    if (v.cueComposers) {
                        
                        cueRec +=  '<span class="hilite">Composer:</span> ';
                    
                        c = [];
                        $.each(v.cueComposers, function(ck,cv) {
                                c.push (cv.FirstName + ' ' + cv.LastName);
                                });
                        cueRec += c.join(' | ');
                    }
                    cueRec +=  '</p></div>';
                
                    cueRec += '  <div class="btns">';
                    cueRec += '      <span class="preview"><a id="new' + v.cueID + '" class="play" rel="' + v.cuePreviewURL + '"></a></span><br />';
                
                    cueRec += '      <a href="javascript:showEyegore(' + v.cueID + ');"><img class="eyegoreBtn" id="btn' + v.cueID + '" src="/qt/images/customize.png" alt="Customize" /></a>';

                    cueRec += '</div>';
                
                    cueRec += '</div><!-- ENd tiTwo -->';
                    cueRec += '<div style="clear: both;" id="trackMark' + v.cueID + '"></div>';
                    cueRec += '</div><!-- END trackInfo -->';
                
                    
                    //cueRec += '</div>';
                    
                    $('#cueList').append(cueRec);
                    
                    $(".preview a").bind('click', aClickPlay);
                }
            });
        }
    }
    }
    $('#showMyMusicSpin').hide();
}



function refreshFilters (data, obj) {
        
    // Empty previous options
    $('#qtFilterSelect'+obj).empty();
    $('#qtFilterValues'+obj).html('');
    
        
    // Populate list box with filter types
    subFilter = '';
    $.each(data.filters, function(k, v)
    {

        $('#qtFilterSelect'+obj).
        append($("<option></option>").
            attr("value",k).
            text(k)); 

        // Make Style options visible
        qtclass = (k == 'Style') ? 'qtFilter qtFilterV' : 'qtFilter';
        subFilter += '<div id="filter'+obj+k+'" class="'+qtclass+'">';

        if (obj == 1) { // If the first filter list is being updated, make the onClick event update the second list
            subFilter += '<SELECT id="f'+obj+'-'+k+'" name="f'+obj+'-'+k+'" MULTIPLE SIZE="6" style="width: 100%;" onClick="getFilters(2);">';
        } else { // If the second filter list is being updated, make the onClick event update both lists
            subFilter += '<SELECT id="f'+obj+'-'+k+'" name="f'+obj+'-'+k+'" MULTIPLE SIZE="6" style="width: 100%;" onClick="getFilters(3);">';    
        }
            
        if (v) {
            $.each(v, function(kk, vv) {
                    
                if (vv.value) {
                    val = vv.value;
                    option = vv.option;
                } else {
                    val = vv;
                    option = vv;
                }
                subFilter += '<option value="'+val+'">'+option+'</option>';
                
            });
        }
            
        subFilter += '</select></div>';
            
    });
        
    $('#qtFilterValues'+obj).html(subFilter);
    
}







function refreshArrangements (data) {

    $('#igorBuildResult').html('');
    if (data) {
        if (data.error) {
            $('#igorBuildResult').html(data.error);
            $('#igorBuildResult').show();
        } else {
            if (data.arrangements) {
                if (data.arrangements.variations) {
                    $.each(data.arrangements.variations, function(k,v) {
                        $.each(v, function(kk,vv) {
                                            
                            if (vv != '') {
                                if (vv) {
                                    $('#variationID').append('<option value="'+vv+'">'+kk+'</option>');
                                }
                            }
                                            
                        });
                                
                    });
                }
                        
                if (data.arrangements.moods) {
                    $.each(data.arrangements.moods, function(k,v) {
                                
                        if (v != '') {
                            if (v) {
                                $('#mood').append('<option> '+v+'</option>');
                            }
                        }
                                
                    });
                }
                $('#eSettings').show();
            }
        
        }
    }
}





function processBuild (data, obj) {
    
    $('#igorBuildResult').html('');
    $('#creditToken').val('');
    if (data) {
        if (data.error) {
            $('#igorBuildResult').html(data.error);
            $('#igorBuildResult').show();
        } else if (data.outfile) {
            if (obj) {
                $('#buyOptions').hide();
                $('#downloadURL').attr('href', data.outfile);
                $('#downloadLink').center();
                $('#downloadLink').show();
                refreshRemaining ();
                
            } else {
                playFlashSong (data.outfile, 'newBuild');
                $('#newBuild').attr('rel', data.outfile);
            }
        }
    }
    

}








function showEyegore (div) {

    $('#downloadList').html('');
    $('#buildButton').html('');

    p = $('#trackMark'+div).position();
    e = $('#eyegore').position();

    $('.eyegoreBtn').each(function(){
        $(this).attr('src', '/qt/images/customize.png');
    });

    /*$('#eSettings').hide();
    $('#eFormat').hide();
*/

    if (p.top == e.top) {
        $('#eyegore').toggle();
    } else {
        $('#eyegore').show();
        $('#variationID').html('');
        $('#mood').html('');
        $('#btn'+div).attr('src', '/qt/images/customizeClose.png');
        $('#btn'+div).attr('src', '/qt/images/customizeClose.png');
        
    }


    $('#eyegore').css('top', p.top);
    $('#cueName').val(div);
    
    if ( $('#eyegore').is(":visible") ) {
        igorSuggest('variationID', 'mood');    
    }
    
    
}




  

function igorSuggest(variations, moods) {
    
    $('#igorSuggest').html('');
    $('#igorMessageInner').html('');
    $('#variationID').html('');
    $('#mood').html('');
    $('#newBuild').attr('rel', '');

    duration =  parseInt(parseInt($('#minutes option:selected').text()*60) + parseInt($('#seconds option:selected').text()));
    $("#minutes").val( 0 ).attr('selected',true);
    
    if (duration > 60) {
      helpDisp('helpLength', false);
      duration =  parseInt(parseInt($('#minutes option:selected').text()*60) + parseInt($('#seconds option:selected').text()));  
    } else {
      $('#helpLength').hide();
    }

    json = '{"cueID":"' + $('#cueName').val() + '","duration":"' + duration + '"}';

    api_returns ('arrangements', json);
    api_returns ('info', json);
  
}


function buildVariation(dl) {

    if ($('#newBuild').hasClass('play')) {
        $('#newBuild').removeClass('play');
    }
    if ( $('#variationID').val() && (! $('#newBuild').attr('rel') || dl) ) {

        json = buildJSON(dl);
        
        if (dl) {
            api_returns ('build', json, 'redir');    
        } else {
            api_returns ('build', json);
        }
        
    }

}

function buildJSON(dl) {
        cue = '"cueID":"' + $('#cueName').val() + '"';
        variation = '"variationID":"' + $('#variationID').val() + '"';
        mood = '"mood":"' + $('#mood').val() + '"';
        $("#minutes").val( 0 ).attr('selected',true);
        
        duration =  '"duration":"' + parseInt(parseInt($('#minutes option:selected').text()*60) + parseInt($('#seconds option:selected').text())) + '"';
        
        
        if (dl) {
            outFormat = $('#typeFile option:selected').text();
            outName = $('#typeFile option:selected').parent().attr('label');
        } else {
            outFormat = 'mp3';
            outName = 'preview';
        }
        
        output = '"output":{"' + outName + '":{"format":"' + outFormat + '"}}';
        trans = '"transData":{"username" : "me", "ipaddress" : "127.0.0.1", "my_user_data" : "QT is awesome!"}';
        
        if ($('#creditToken').val()) {
            token = '"token":"' + $('#creditToken').val() + '"';    
            return "{" + token + "," + cue + "," + duration + "," + variation +  "," + mood + "," + output + "," + trans + "}";
        } else {
            return "{" + cue + "," + duration + "," + variation +  "," + mood + "," + output + "," + trans + "}";    
        }
        
}





function showFilterOptions(div, id) {
    opt = $('#qtFilterSelect'+id).val();
    $('#qtFilterValues'+id).children("div").hide();
    $('#'+div+opt).show();
}




function showFormat() {
    if ($('#newBuild').attr('rel') != '' ) {
        $('#eFormat').show();
    }
}

function showBuyOptions() {
    
    $('#purchaseURL').attr('href', '?json='+buildJSON());
    
    $('#buyOptions').center();
    $('#buyOptions').show();
}

function showMyMusic() {
    $('#showMyMusicSpin').show();
    
    $('.qtFilter').children('select').children("option:selected").removeAttr("selected");
    $('#search_input').val('');
    
    if ($('#showmine').val() == 1) {
        $('#showmine').val(0);
        $('#showMyMusic').html('<img src="images/showMy.png" alt="show My Tracks" />');
    } else {
        $('#showmine').val(1);
        $('#showMyMusic').html('<img src="images/showAll.png" alt="show All Tracks" />');
    }
    getFilters(2);
    $('#eyegore').hide();
}


function resetNewBuild() {
    $('#newBuild').attr('rel', '');
}

function refreshRemaining () {
    $.get("/qt/quicktracks-remaining.html", function(data){
                $("#qtDLRemaining").html(data);
            });
}
function refreshDownloadList (cueid) {
    $.get("/qt/quicktracks-download.html", function(data){
                $("#downloadList").html(data);
            });
    refreshRemaining ();
}

function refreshInfo (data) {

    if (data) {
        if (data.error) {
            $('#igorBuildResult').html(data.error);
            $('#igorBuildResult').show();
        } else {
            if (data.info) {
                if (data.info.button == 'buy') {
                    $('#buildButton').attr('href', data.info.href);
                    $('#buildButton').attr('target', '_blank');
                    if (data.info.price) {
                        $('#buildButton').html('<img align="left" style="margin-right: 10px;" src="images/qtBuyBtn.png" alt="Buy" /> for $' + data.info.price);
                    } else {
                        $('#buildButton').html('<img src="images/qtBuyBtn.png" alt="Buy" />');
                    }
                } else if (data.info.button == 'incart') {    
                    $('#buildButton').attr('href', data.info.href);
                    $('#buildButton').attr('target', '_blank');
                    $('#buildButton').html('<img src="images/inCart.png" alt="In Cart" />');
                } else {
                    $('#buildButton').attr('href', "javascript:buildVariation('dl');");
                    $('#buildButton').attr('target', '');
                    $('#buildButton').html('<img src="images/eyeDownload.png" alt="Download" />');                    
                }
            }
            
        }
    }
    
}

function showMainLoader() {
    $("#mainLoadingImg").show();
}
function clearMainLoader() {
    $("#mainLoadingImg").hide();
}
function toggleDiv(div) {
    $("#"+div).toggle();
}



