/* cmmimarlik.com.tr 2011 */

var cm = {

    rootUrl : '',
    projectUrl : '',
    projectTypes : [],
    projectDates: [],
    typeIdRelationships: {},
    dateIdRelationships: {},
    currentType : '',
    currentDate : '',
    filteredIds : [],
    projectFilter : {

        selectAllString: '',
        typologicalString: '',
        chronologicalString: '',
        filterType: '',
        ready: function(opt) {

            this.selectAllString = opt.selectAllString;
            this.typologicalString = opt.typologicalString;
            this.chronologicalString = opt.chronologicalString;
            this.tableType = opt.tableType;

            this.rootUrl = opt.rootUrl;
            this.projectUrl = opt.projectUrl;
            this.projectTypes = opt.projectTypes;
            this.projectDates = opt.projectDates;
            this.typeIdRelationships = opt.typeIdRelationships;
            this.dateIdRelationships = opt.dateIdRelationships;

        },
        ui: {
            selectAllButton : function(selectType) {
                var href = '#';
                if (selectType == 'type') {
                    href += cm.currentDate + ':all';
                } else {
                    href += 'all:' + cm.currentType;
                }

                return '<li><a style="font-weight: bold;" href="' + href + '">' + selectAllString + '</a></li>';
            },
            generateFilterItems: function(selectType) {
                

            }
        }
    }
};

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

function summ2() {

    var sum = 0,
            completedSum = 0;

    $('.project-m2-td').each(function() {
        var value = parseInt($(this).html().replace('.', ''));
        if (!isNaN(value)) {
            sum = sum + value;
        }
    });

    $('.project-status.status-1').each(function() {
        var value = parseInt($(this).parent().parent().find('.project-m2-td').html().replace('.', ''));
        if (!isNaN(value)) {
            completedSum = completedSum + value;
        }
    });

    var sumRow = '<tr class="jqgrow ui-row-ltr no-hover"><td colspan="4"></td><td colspan="2" style="text-align: right;">' + addCommas(sum) + ' M²</td></tr>',
            completedSumRow = '<tr class="jqgrow ui-row-ltr no-border no-hover"><td colspan="4"></td><td colspan="2" style="text-align: right;"><div class="project-status status-1" style="float: left;"></div>' + addCommas(completedSum) + ' M²</td></tr>';

    $('#project-list').append(sumRow).append(completedSumRow);
}

var _gridLoadCompleted = 0;
function sortGrid() {

    if (!_gridLoadCompleted) {
        setTimeout(function() {
            $("#project-list").setGridParam({sortname: 'date',sortorder: 'desc'}).trigger('reloadGrid');
        }, 1)
        _gridLoadCompleted = 1;
    }

}

function toProject(rowid, status) {

    if (typeof(_project_single_link) == 'undefined') {
        return;
    }

    window.location = _project_single_link + rowid;
}

function projectStatus(cellvalue, options, rowObject) {

    return '<div class="project-status status-' + cellvalue + '">' + cellvalue + '</div>';

}

var __currentDate = 'all',
        __currentType = 'all';

function projectFilters() {

    var projectTypeList = $('#project-types');
    if (typeof(_project_types) != 'undefined') {
        if (_project_types.length == 0) return;

        projectTypeList.html('');

        if (__currentType != 'all') {
            projectTypeList.append('<li><a style="font-weight: bold;" href="#' + __currentDate + ':all">' + _select_all + '</a></li>');
        }

        for (var i = 0; i < _project_types.length; i ++) {
            projectTypeList.append('<li><a ' + (_project_types[i].split('|')[1] == __currentType ? 'class="current"' : '') + ' href="#' + __currentDate + ':' + _project_types[i].split('|')[1] +
                    '">' + _project_types[i].split('|')[0] + '</a></li>'
            );
        }
    }

    var projectDateList = $('#project-dates');
    if (typeof(_project_dates) != 'undefined') {
        if (_project_dates.length == 0) return;

        projectDateList.html('');

        if (__currentDate != 'all') {
            projectDateList.append('<li><a style="font-weight: bold;" href="#all:' + __currentType + '">' + _select_all + '</a></li>');
        }

        for (var i = 0; i < _project_dates.length; i ++) {
            projectDateList.append('<li><a ' + (_project_dates[i] == __currentDate ? 'class="current"' : '') + ' href="#' + _project_dates[i] + ':' + __currentType + '">' + _project_dates[i] + '</a></li>');
        }
    }

}

function projectFilterClick() {

    $(window).bind('hashchange', function(e) {

        var hash = $.param.fragment(),
                dateFilteredIds = [],
                typeFilteredIds = [],
                theseIdsGoingToFiltered = [];

        var hashParts = hash.split(':');

        if (hashParts.length == 2) {
            var hashedYear = hashParts[0],
                    hashedType = hashParts[1];

            __currentDate = hashedYear;
            __currentType = hashedType;

            if (__currentDate != 'all') {
                $("#selected-project-date").html(__currentDate);
            } else {
                $("#selected-project-date").html(_date_select_header);
            }

            if (__currentType != 'all') {
                for (var pt = 0; pt < _project_types.length; pt++) {

                    var currentProjectType = _project_types[pt],
                            splittedCurrentProjectType = currentProjectType.split('|');

                    if (splittedCurrentProjectType[1] == __currentType) {
                        $("#selected-project-type").html(splittedCurrentProjectType[0]);
                        break;
                    }

                }
            } else {
                $("#selected-project-type").html(_type_select_header);
            }

            if (hashedYear != 'all' && typeof(_project_date_ids[hashedYear]) !== 'undefined') {
                dateFilteredIds = _project_date_ids[hashedYear];
            }

            if (hashedType != 'all' && typeof(_project_type_ids[hashedType]) !== 'undefined') {
                typeFilteredIds = _project_type_ids[hashedType];
            }

            if (typeFilteredIds.length > 0 && dateFilteredIds.length > 0) {

                for (var t = 0; t < typeFilteredIds.length; t++) {
                    for (var d = 0; d < dateFilteredIds.length; d++) {

                        if (typeFilteredIds[t] == dateFilteredIds[d]) {

                            theseIdsGoingToFiltered.push(typeFilteredIds[t]);

                        }

                    }
                }

            } else if (typeFilteredIds.length > 0) {

                theseIdsGoingToFiltered = typeFilteredIds;

            } else if (dateFilteredIds.length > 0) {

                theseIdsGoingToFiltered = dateFilteredIds;

            }

            function filterTable() {
                $('#project-list tr:not(tr.jqgfirstrow,#' + theseIdsGoingToFiltered.join(',#') + ')').hide(function() {

                    $('#' + theseIdsGoingToFiltered.join(',#')).show();

                });
            }

            if (theseIdsGoingToFiltered.length > 0) {

                if ($('#project-list').length) {

                    if (_gridLoadCompleted) {

                        filterTable();

                    } else {

                        setTimeout(filterTable, 100);

                    }

                } else {
                    $('#project-thumb-list li:not(#' + theseIdsGoingToFiltered.join(',#') + ')').hide(function() {

                        $('#' + theseIdsGoingToFiltered.join(',#')).fadeIn('slow');

                    });
                }
            } else if (__currentDate == 'all' && __currentType == 'all') {

                if ($('#project-list').length) {

                    $('#project-list tr').show();

                } else {

                    $('#project-thumb-list li').fadeIn('slow');

                }

            }

            //console.log(theseIdsGoingToFiltered);

            projectFilters();

        }

    });

    $(window).trigger('hashchange');

}

$(function() {

    $('#main-slider').cycle({
        fx: 'fade',
        speed: 1500,
        timeout: 6000,
        pause : 1
    });

    $('#about-images').cycle({
        fx: 'fade',
        speed: 1500,
        timeout: 6000
    });

    function pagerFactory(idx, slide) {
        return '<li><a href="#">' + (idx + 1) + '</a></li>';
    }

    $('#project-images').cycle({
        fx: 'fade',
        speed: 1500,
        timeout: 6000,
        pager: '#project-image-navigation',
        pagerAnchorBuilder: pagerFactory
    });

    var titleWidth = 366,
            dateWidth = 145,
            typeWidth = 145,
            locationWidth = 145,
            statusWidth = 68,
            m2Width = 61;

    if ($.browser.webkit) {
        titleWidth = 372;
        dateWidth = 150;
        typeWidth = 150;
        locationWidth = 150;
        statusWidth = 68;
        m2Width = 70;
    }

    var rootUrl = '';
    if (typeof(_root_url) !== 'undefined') {
        rootUrl = _root_url;
    }

    var __colNames = ['Project Name','Year','Type','Location','Status','M²'];
    if (typeof(_colNames) !== 'undefined') {
        __colNames = _colNames;
    }

    $("#project-list").jqGrid({
        url: rootUrl + '/projects/projects-json-data/',
        datatype: 'json',
        colNames: __colNames,
        colModel:[
            {name:'title',index:'title',width:titleWidth,classes:'project-title-td',sortable:true},
            {name:'date',index:'date', width:dateWidth,classes:'project-date-td',sorttype:"date"},
            {name:'type',index:'type',width:typeWidth,classes:'project-type-td',sortable:true},
            {name:'location',index:'location',width:locationWidth,classes:'project-location-td',sortable:true},
            {name:'status',index:'status',width:statusWidth,classes:'project-status-td',formatter: projectStatus},
            {name:'m2',index:'m2',width:m2Width,classes:'project-m2-td',sorttype:"int"}
        ],
        rowNum: 999,
        sortname: 'date',
        sortorder: 'desc',
        viewrecords: true,
        loadonce: true,
        height: 'auto',
        gridComplete: summ2,
        loadComplete: sortGrid,
        onSelectRow: toProject
    });

    $('.press_images').fancybox({
        titlePosition: 'inside',
        transitionIn : 'fade',
        transitionOut : 'fade'
    });

    projectFilters();

    projectFilterClick();

});
