

function plusAction(plusClass, holder, clearThis){
    $(plusClass).unbind('click');
    $(plusClass).click(function(){
        $(holder).show();
        $(plusClass).html('[-]');
        $(plusClass).removeClass('plus').addClass('minus');
        minusActions(plusClass, holder, clearThis);
    });
}
function minusActions(plusClass, holder, clearThis){
    $(plusClass).unbind('click');
    $(plusClass).click(function(){
        $(holder).hide();
        $(plusClass).html('[+]');
        $(plusClass).removeClass('minus').addClass('plus');
        $(clearThis).val('');
        plusAction(plusClass,holder, clearThis);
    });
}


var facebookAppId = '105751029506835';
//var baseDir = 'http://dev6.atesinternational.ch/';
var skin = 'default';
var loggedIn = false;
var playedIcon = baseDir + 'skins/' + skin + '/images/played.png';
var plannedIcon = baseDir + 'skins/' + skin + '/images/planned.png';
var allIcon = baseDir + 'skins/' + skin + '/images/all.png';
var mapShowing = 'none';
var statusLastId = 0;
var statusLastStatus = 0;
var ajaxReq = 0;
var lastLat = 0;
var lastLng = 0;

function openInviteViaEmailWindow(){
    
}

function SatelliteView(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/setsat",
        data: null,
        success: function(data){}
    });
}

function MapView(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/setmap",
        data: null,
        success: function(data){}
    });
}

function refreshPoints(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/getpoints",
        data: null,
        success: function(data){
            $("#pointsholder").html(data);
        }
    });
}
function loadPhotos(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/myphotos",
        data: null,
        success: function(data){
            $("#myphotos").html(data);
            $('.deletePhoto').click(function(){
                if(confirm("Are you sure that you want to delete this photo?")){
                    $.ajax({
                        type: "POST",
                        url: baseDir + "ajax/deletephoto",
                        data: {
                            pic: $(this).attr('pic_id')
                        },
                        success: function(data){
                        //Good one!
                        }
                    });
                    $("#file_holder_"+$(this).attr('pic_id')).hide();
                }
            });
            $('.profilePhoto').click(function(){
                if(confirm("Are you sure that you want to set this photo as profile photo?")){
                    $.ajax({
                        type: "POST",
                        url: baseDir + "ajax/setprofile",
                        data: {
                            pic: $(this).attr('pic_id')
                        },
                        success: function(data){
                        //Good one!
                        }
                    });
                }
            });
        }
    });
}
function gplayersAction(){
    $.ajax({
        url: baseDir + "ajax/gplayers",
        dataType: "html",
        data: {
        },
        success: function( data ) {
            Shadowbox.open({
                content:    data,
                player: 'html',
                title:      " ",
                height:     400,
                width:      500,
                options: {
                    enableKeys: false
                }
            });
            $('.closePopup').click(function(){
                Shadowbox.close();
            });
            $('.closeBtnBox').click(function(){
                Shadowbox.close();
            });
        //             $('.emailShare').click(emailShareClick);
        //            $('.fbShare').click(function(){
        //                fbShareClick('s',$(this).attr('f_pic'));
        //            });
        //            $('.mailInvite').click(mailInviteClick);
        //            $('.fbInvite').click(fbInviteClick);
        }
    });
//    $.ajax({
//        type: "POST",
//        url: "ajax/gplayers",
//        data: null,
//        success: function(data){
//            $("#gallerydiv").html(data);
//            $('.closePopup').click(function(){
//                $("#gallerydiv").html('');
//            });
//        }
//    });
}
function ggreenkeepersAction(){
    //    $.ajax({
    //        type: "POST",
    //        url: "ajax/ggreenkeepers",
    //        data: null,
    //        success: function(data){
    //            $("#gallerydiv").html(data);
    //            $('.closePopup').click(function(){
    //                $("#gallerydiv").html('');
    //            });
    //        }
    //    });
    $.ajax({
        url: baseDir + "ajax/ggreenkeepers",
        dataType: "html",
        data: {
        },
        success: function( data ) {
            Shadowbox.open({
                content:    data,
                player: 'html',
                title:      " ",
                height:     135,
                width:      360,
                options: {
                    enableKeys: false
                }
            });
            $('.closePopup').click(function(){
                Shadowbox.close();
            });
            $('.closeBtnBox').click(function(){
                Shadowbox.close();
            });
        //             $('.emailShare').click(emailShareClick);
        //            $('.fbShare').click(function(){
        //                fbShareClick('s',$(this).attr('f_pic'));
        //            });
        //            $('.mailInvite').click(mailInviteClick);
        //            $('.fbInvite').click(fbInviteClick);
        }
    });
}
function goGreen(cid, hid){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/begreenkeeper",
        data: {
            cid: cid,
            hid: hid
        },
        success: function(data){
            if(data == 'OK'){
                alert('You have changed your greenkeeper status!');
                loadClubInfo(cid);
                loadRightSidebar(cid);
            }
            else{
                alert(data);
            }
        }
    });
}
function addCourse(cid){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/addcourse",
        data: {
            cid: cid
        },
        success: function(data){
            refreshPoints();
        //          alert('You have added this course to your list of courses!');
        }
    });
}
function deleteCourse(cid){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/delete-course",
        data: {
            cid: cid
        },
        success: function(data){
            loadCourseList($('#pagin_current').val());
            loadAllCourses(true);
            refreshPoints();
        }
    });
}
function emailShareClick(){
    var email = $('#input_email').val();
    if(email.length < 1)
        alert('Please insert e-mail!');
    //Todo validate e-mail
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/mailshare",
        data: {
            mail: $('#input_email').val()
        },
        success: function(data){
            if(data == 'OK')
                alert('Sent mail!');
            else
                alert(data);
        }
    });
}
function loadMcsByPage(page){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/searchmcs",
        data: {
            country: $('#mcs_country').val(),
            city: $('#mcs_city').val(),
            name: $('#mcs_name').val(),
            address: $('#mcs_address').val(),
            page: page
        },
        success: function(data){
            $("#resultsMCS").html(data);
            $(".hideResultsMCS").click(function(){
                $("#resultsMCS").html('');
            });
            $('.addCourt').click(function(){
                var id = this.id.replace('mcs_add_course_','');
                addCourse(id);
                $("#mcs_add_course_"+id).removeClass('addCourt').addClass('checkedCourt');
            });
            $.ajax({
                type: "POST",
                url: baseDir + "ajax/paginationmcs",
                data: {
                    page: page
                },
                success: function(data){
                    $('#paginacijamcs').html(data);
                    $('.paginlink').click(function(){
                        loadMcsByPage($(this).attr('page')); 
                    });
                }
            });
        }
    });
}
function searchMCS(){
    var page = 1;
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/searchmcs",
        data: {
            country: $('#mcs_country').val(),
            city: $('#mcs_city').val(),
            name: $('#mcs_name').val(),
            address : $('#mcs_address').val(),
            page: page
        },
        success: function(data){
            $("#resultsMCS").html(data);
            $(".hideResultsMCS").click(function(){
                $("#resultsMCS").html('');
            });
            $('.addCourt').click(function(){
                var id = this.id.replace('mcs_add_course_','');
                addCourse(id);
                
                $("#mcs_add_course_"+id).removeClass('addCourtMoje');
                $("#mcs_add_course_"+id).removeClass('addCourt').addClass('checkedCourt');
            });
            $.ajax({
                type: "POST",
                url: baseDir + "ajax/paginationmcs",
                data: {
                    page: page
                },
                success: function(data){
                    $('#paginacijamcs').html(data);
                    $('.paginlink').click(function(){
                        loadMcsByPage($(this).attr('page')); 
                    });
                }
            });
        }
    });
}
function showMultipleCoursesScreen(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/mcourses",
        data: null,
        success: function(data){
            $("#mcoursesdiv").html(data);
            $("#mcoursesdiv").draggable();
            $('.coolinput').click(function(){
                if(this.value == $(this).attr('vrednost'))
                    this.value = '';
            });
            $('.coolinput').blur(function(){
                if(this.value == '')
                    this.value = $(this).attr('vrednost');
            });
            $('.searchMCS').click(searchMCS);
            $('.closeMCS').click(function(){
                $("#mcoursesdiv").html(''); 
            });
            //            $("#mcs_city").live('keyup',function(){
            //            });
            
            $('.reportLink').click(reportClick);
            $('.alternativeReport').click(alernativeReport);
            $('#mcs_city').autocomplete(baseDir + "ajax/get-cities/");
            $('#mcs_country').autocomplete(baseDir + "ajax/get-countries/");
            $("#mcs_country").live('keyup',function(){});
                
        //                $(".courseInput").autocomplete(baseDir + "ajax/search");
        /*OVDE AUTOCOMPLETE*/
        }
    });
}
function changeStatus(id, status){
    //    if(statusLastId == id && statusLastStatus == status)
    //        return;
    statusLastId = id;
    statusLastStatus = status;
    if(status == 1){
        $('.'+id).removeClass('playedButton').removeClass('infoButton').addClass('plannedButton');
    //        $('.plannedButton').click(function(){ changeStatus(id, 2) });
    }
    else{
        $('.'+id).removeClass('plannedButton').addClass('playedButton');
    //        $('.playedButton').click(function(){ changeStatus(id, 1); });
    }
    var arr = id.split('_');
    
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/changestatus",
        data: {
            oid: arr[3],
            status: status
        },
        success: function(data){
            loadClubInfo(arr[3]);
            refreshPoints();
            addFlagById(arr[3],status);
            showRating();
        }
    });
    $('.infoButton').unbind("click");
    $(".plannedButton").unbind("click");
    $(".playedButton").unbind("click");
    $('.infoButton').click(function(){
        changeStatus(this.id, 1);
    });
    $('.plannedButton').click(function(){
        changeStatus(this.id, 2);
    });
    $('.playedButton').click(function(){
        changeStatus(this.id, 1);
    });
    loadClubInfo(arr[3]);
    loadCourseList($('#pagin_current').val());
    showRating();
}

function changeStatusProfile(id, status){
    if(statusLastId == id && statusLastStatus == status)
        return;
    statusLastId = id;
    statusLastStatus = status;
    if(status == 1){
        $('.'+id).removeClass('playedButton').removeClass('infoButton').addClass('plannedButton');
    //        $('.plannedButton').click(function(){ changeStatus(id, 2) });
    }
    else{
        $('.'+id).removeClass('plannedButton').addClass('playedButton');
    //        $('.playedButton').click(function(){ changeStatus(id, 1); });
    }
    var arr = id.split('_');
    
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/changestatus",
        data: {
            oid: arr[3],
            status: status
        },
        success: function(data){
            loadClubInfo(arr[3]);
            refreshPoints();
            addFlagById(arr[3],status);
        }
    });
    $('.infoButton').unbind("click");
    $(".plannedButton").unbind("click");
    $(".playedButton").unbind("click");
    $('.infoButton').click(function(){
        changeStatus(this.id, 1);
    });
    $('.plannedButton').click(function(){
        changeStatus(this.id, 2);
    });
    $('.playedButton').click(function(){
        changeStatus(this.id, 1);
    });
    loadCourseListProfile(1);
}

function addFlagById(id, status){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/getflagdata",
        data: {
            oid: id
        },
        success: function(data){
            //            loadClubInfo(arr[3]);
            //            refreshPoints();
            
            var todo = {
                action:'clear'
            };
            todo['name'] = 'marker'; 
            $('#map').gmap3(todo);
            var result = JSON.parse(data);
            var lat = result[0]['latitude'];
            var lng = result[0]['longitude'];
            if(status == 2){
                addPlayedMarker(lat, lng, result[0]['gid']);
            }
            else{
                addPlannedMarker(lat, lng, result[0]['gid']);
            }
        }
    });
}

function closeInfoBox(){
    stopedLooking();
    $("#clubBox").html('');
}
function createUploader(action){   
    var uploader = new qq.FileUploader({
        element: document.getElementById('file-uploader'),
        action: action,
        multiple: false,
        debug: true,
        params: {
            us:'yes'
        },
        onSubmit: function(id, fileName){
            
        },
        onComplete: function(id, fileName, content_data){
            loadClubInfo($('#current_object_id').val());
            loadRightSidebar($('#current_object_id').val());
        },
        template:'<div class="qq-uploader">' + 
    '<div class="qq-upload-button">Upload image</div>' +
    '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
    '<ul class="qq-upload-list"></ul>' + 
    '</div>'
    });
}
function rateCourse(courseId, rating){
    if(rating > 10 || rating < 0)
        return;
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/ratecourse",
        data: {
            course: courseId,
            rating: rating
        },
        success: function(data){
            loadCourseList($('#pagin_current').val());
            loadClubInfo(courseId);
        //Good one!
        //            shareToWall(
        //                'Rated a course at Golfoon', 
        //                'Golfoon', 
        //                'Rated a course at Golfoon', 
        //                baseDir, 
        //                '', 
        //                'Build your own Golf map.'
        //                );
        }
    });
}
function loadRightSidebar(cid){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/rightsidebar",
        data: {
            cid:cid
        },
        success: function(data){
            $("#rightSidebar").html(data);
            $('.gMore').click(ggreenkeepersAction);
            $('.pMore').click(gplayersAction);
        }
    });
}
function mapZoomIn(lat, lng, type){
    var newLng = (+lng);
    var movedLng = newLng + 0.025;
    lastLat = lat;
    lastLng = lng;
    $('#map').gmap3(
    {
        action: 'addMarker',
        latLng: [lat, movedLng],
        map:{
            center: [lat, lng],
            zoom: 13
        },
        marker:{
            options:{
                icon: playedIcon,
                draggable: true
            }
        }
    }); 
    clearLast();
}
function showRating(){
    //    alert('#1');
    //    $("#clubBox .rate_course").children().not(":radio").hide();
    //    alert('#2');
    $("#clubBox .rate_course").stars({
        inputType: "radio",
        split: 2,
        captionEl: $("#stars-wrapper1-cap"),
        callback: function(ui, type, value){
            var arr = value.split('_');
            rateCourse(arr[2], arr[3]);
        }
    });
    //    alert('#3');
    //    $(".rate_course").children().not(":radio").hide();
    //    alert('#4');
    //    $(".rate_course").stars({
    //        inputType: "radio",
    //        split: 2,
    //        captionEl: $("#stars-wrapper1-cap"),
    //        callback: function(ui, type, value){
    //            var arr = value.split('_');
    //            rateCourse(arr[2], arr[3], arr[4]);
    //        }
    //    });
    //    alert('#5');
    $('.rate_course').each(function(){
        //        alert('#5.1');
        //        alert($(this).attr('id'));
        try{
            $(this).stars({
                inputType: "radio",
                split: 2,
                //            captionEl: $("#stars-wrapper1-cap"),
                callback: function(ui, type, value){
                    var arr = value.split('_');
                    rateCourse(arr[2], arr[3], arr[4]);
                }
            });
        } catch (e) {
        
        }
    //        alert('#5.2');
    });
    //    alert('#6');
    $(".rate_course").show();
    $(".ui-stars-star").show();
    $(".ui-stars-star-on").show();
    $("#clubBox .rate_course").show();
//    alert('#7');
}
function loadClubInfoJSON(cid){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/clubdescjson",
        data: {
            cid:cid
        },
        success: function(data){
            
            var result = JSON.parse(data);
            //            alert(result['img_src']);
            
            $('.clubBoxClubImage').src = result['img_src'];
            $('.boxSubHeader').html(result['name']);
            $('#reportClubBox').html(
                '<a id="report_id_'+result['gid']+'" class="reportCourse">Report course</a>'
                );
            
            showRating();
        }
    });
    showRating();
}
function loadClubInfo(cid, showMe){
    if( typeof(showMe) == 'undefined' ){
        showMe = 0;
    }
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/clubdesc",
        data: {
            cid:cid,
            show: showMe
        },
        success: function(data){
            //            alert('#1');
            //            alert('#1');
            //            alert(data);
            try{
                $("#clubBox").html(data); 
            } catch(e) {
                
            }
            
            //            alert('#1');
            $('#clubBox .ratingDiv').each(function(index, value) { 
                //                alert(index);
                //                alert(value);
                //                alert($(value).html());
                //                var value = this.id;
                var val = $(this).attr('id');
                var arr = val.split('_');
                var currentId = arr[2];
                var played = $('#course_dt_status_' + currentId).hasClass('playedButton');
                var planned = $('#course_dt_status_' + currentId).hasClass('plannedButton');
                if(played){
                    addPlayedMarker(lastLat, lastLng, currentId);
                } else if( planned ) {
            //                    addPlannedMarker(lastLat, lastLng, currentId);
            }
            });
            
            //            alert('#2');
            $('.plannedButton').click(function(){
                changeStatus(this.id, 2);
            });
            
            //            alert('#3');
            $('.playedButton').click(function(){
                changeStatus(this.id, 1);
            });
            
            //            alert('#4');
            createUploader('upload/courseimg');
            
            //            alert('#5');
            $('#current_object_id').val(cid);
            
            //            alert('#6');
            $('.closeBtnBox').click(closeInfoBox);
            $('.reportClub').click(reportClubClick);
            
            //            alert('#8');
            $('.clubBoxSelectCourse').change(function(){
                var value = this.value;
                var name = $("#info_"+value).attr('obj_name');
                var img = $("#info_"+value).attr('obj_img');
                var type = $("#info_"+value).attr('obj_type');
                if(type < 3){
                    loadClubInfo(value, 1);
                } else {
                    //                    alert(name);
                    //                    $('.clubBoxClubImage').src = img;
                    $('.clubBoxClubImage').attr("src", img);
                    $('.boxSubHeader').html(name);
                    $('#reportClubBox').html(
                        '<a id="report_id_'+value+'" class="reportCourse">Report course</a>'
                        );
                    $('.reportCourse').click(reportCourseClick);
                    $('.ratingDiv').hide();
                    $("#rating_div_"+value).show();
                    $('.greenkeeperDiv').hide();
                    $("#green_keeper_div_"+value).show();
                    showRating();
                //                    $('.clubBoxSubHeaderHolder').html($("#rating_div_"+value).html());
                }
                loadRightSidebar(value);
            });
            
            //            alert('#9');
            $('.infoButton').click(function(){
                changeStatus(this.id, 1);
            });
            $('.plannedButton').click(function(){
                changeStatus(this.id, 2);
            });
            $('.playedButton').click(function(){
                changeStatus(this.id, 1);
            });
            
            //            alert('#10');
            $('.clubBoxGreenkeeperSelect').change(function(){
                var value = this.value;
                var arr = value.split('_');
                var isGreen = $("#isgreen").val();
                //                alert(isGreen);
                var at = $("#isgreen").attr('g_text');
                if(isGreen == 1){
                    if(confirm(
                        'You are already green keeper at ' + at + '. Do you realy want to change that?'
                        )){
                        goGreen(arr[0], arr[1]);
                    }
                    else{
                        return;
                    }
                }
                else
                    goGreen(arr[0], arr[1]);
            });
            
            //            alert('#11');
            showRating();
            refreshPoints();
            
        //            alert('#12');
        }
    });
    showRating();
}

function flagClick(data){
    clearMarkers();
    //    alert('BILO STA!');
    //    alert(data.lat + "/" + data.lng);
    mapZoomIn(data.lat, data.lng, data.type);
    loadRightSidebar(data.cid);
    loadClubInfo(data.cid);
    showRating();
}
function tableItemClick(lat, lng, cid){
    clearMarkers();
    mapZoomIn(lat, lng, 'sss');
    loadRightSidebar(cid);
    loadClubInfo(cid);
    showRating();
}
function addPlannedMarker(latitude, longitude, course_id){
    $('#map').gmap3(
    {
        action: 'addMarkers',
        markers:[
        {
            lat:latitude, 
            lng:longitude, 
            data:{
                lat: latitude,
                lng: longitude,
                cid: course_id,
                type: plannedIcon
            }
        }
        ],
        marker:{
            options:{
                icon: plannedIcon
            //                ,animation: google.maps.Animation.DROP
            },
            events:{
                click: function(marker, event, data){
                    flagClick(data);
                }
            }
        }
    });   
}
function addPlayedMarker(latitude, longitude, course_id){
    var i;
    $('#map').gmap3(
    {
        action: 'addMarkers',
        markers:[
        {
            lat:latitude, 
            lng:longitude, 
            data:{
                lat: latitude,
                lng: longitude,
                cid: course_id,
                type: playedIcon
            }
        }
        ],
        latLng:[latitude,longitude],
        marker:{
            options:{
                icon: playedIcon
            //                ,animation: google.maps.Animation.DROP
            },
            events:{
                click: function(marker, event, data){
                    flagClick(data);
                }
            }
        }
    });   
}
function addNeutralMarker(latitude, longitude, course_id){
    /*
     *$('#map').gmap3({
        action: 'addMarkers',
        markers:[
        {
            lat:lat, 
            lng:lng, 
            tag : "search-results",
            data:{
                lat: lat,
                lng: lng,
                type: flag,
                gid: gid
            }
        }
        ],
        marker:{
            options:{
                draggable: true,
                icon: flag,
                animation: google.maps.Animation.DROP
            },
            events:{
                dragend: function(marker, event){
                },
                click: function(marker, event, data){
                    showEditObjectForm(data.gid);
                //                    alert();
                }
            }
        }
    });
     **/
    $('#map').gmap3(
    {
        action: 'addMarkers',
        markers:[
        {
            lat:latitude, 
            lng:longitude, 
            tag : "search-results",
            data:{
                lat: latitude,
                lng: longitude,
                cid: course_id,
                type: allIcon
            }
        }
        ],
        latLng:[latitude,longitude],
        marker:{
            options:{
                icon: allIcon
            //                ,animation: google.maps.Animation.DROP
            },
            events:{
                click: function(marker, event, data){
                    flagClick(data);
                }
            }
        }
    }); 
}
function showLoadingMessage(){
    $('#course_list').html($("#loading_display").html());
    $('#course_list_profile').html($("#loading_display").html());

}
function hideLoadingMessage(){
    $('#course_list').html();
    $('#course_list_profile').html();
}
function loadCourseListProfileByParams(page, sortType, sortDirection, searchQuery){
    showLoadingMessage();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/dtcourselistprofile",
        data: {
            page:page,
            search: searchQuery,
            sort_type: sortType,
            sort_direction : sortDirection
        },
        success: function(data){
            $('#course_list_profile').html(data);
            $('.sorting').click(function(){
                var value = this.id;
                var arr = value.split('_');
                var page = $('#pagin_current').val();
                var sortType = arr[1];
                var sortDirection = arr[2];
                var searchQuery = $('.coursesLookup').val();
                loadCourseListProfileByParams(page,sortType,sortDirection,searchQuery);
            });
            
            $('.searchBtnDT').click(function(){
                var page = $('#pagin_current').val();
                var sortType = $('#pagin_sort_type').val();
                var sortDirection = $('#pagin_sort_dir').val();
                var searchQuery = $('.coursesLookup').val();
                loadCourseListProfileByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.tableItem').click(function(){
                tableItemClick($(this).attr('lat'), $(this).attr('lng'), $(this).attr('cid'));
            });
            showRating();
            paginLinksProfile();
        }
    });
    showRating();
}
function loadCourseListByParams(page, sortType, sortDirection, searchQuery){
    showLoadingMessage();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/dtcourselist",
        data: {
            page:page,
            search: searchQuery,
            sort_type: sortType,
            sort_direction : sortDirection
        },
        success: function(data){
            $('#coursesList').html(data);
            $('.sorting').click(function(){
                var value = this.id;
                var arr = value.split('_');
                var page = $('#pagin_current').val();
                var sortType = arr[1];
                var sortDirection = arr[2];
                var searchQuery = $('.coursesLookup').val();
                loadCourseListByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.searchBtnDT').click(function(){
                var page = $('#pagin_current').val();
                var sortType = $('#pagin_sort_type').val();
                var sortDirection = $('#pagin_sort_dir').val();
                var searchQuery = $('.coursesLookup').val();
                loadCourseListByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.tableItem').click(function(){
                tableItemClick($(this).attr('lat'), $(this).attr('lng'), $(this).attr('cid'));
            });
            showRating();
            $('.deleteCourse').click(function(){
                var value = this.id;
                var arr = value.split('_');
                var cid = arr[2];
                deleteCourse(cid);
            });            
            paginLinks();
        }
    });
    showRating();
}
function loadCourseListProfile(page){
    showLoadingMessage();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/dtcourselistprofile",
        data: {
            page:page,
            search: $('.coursesLookup').val(),
            sort_type: '',
            sort_direction : ''
        },
        success: function(data){
            $('#course_list_profile').html(data);
            $('.sorting').click(function(){
                var value = this.id;
                var arr = value.split('_');
               
                var page = $('#pagin_current').val();
                var sortType = arr[1];
                var sortDirection = arr[2];
                var searchQuery = $('.coursesLookup').val();
                loadCourseListProfileByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.searchBtnDT').click(function(){
                var page = $('#pagin_current').val();
                var sortType = $('#pagin_sort_type').val();
                var sortDirection = $('#pagin_sort_dir').val();
                var searchQuery = $('.coursesLookup').val();
                loadCourseListProfileByParams(page,sortType,sortDirection,searchQuery);
            });
            showRating();
            paginLinksProfile();
        }
    });
    showRating();
}
function loadCourseList(page){
    showLoadingMessage();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/dtcourselist",
        data: {
            page:page,
            search: $('.coursesLookup').val(),
            sort_type: '',
            sort_direction : ''
        },
        success: function(data){
            $('#coursesList').html(data);
            $('.sorting').click(function(){
                var value = this.id;
                var arr = value.split('_');
               
                var page = $('#pagin_current').val();
                var sortType = arr[1];
                var sortDirection = arr[2];
                var searchQuery = $('.coursesLookup').val();
                loadCourseListByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.searchBtnDT').click(function(){
                var page = $('#pagin_current').val();
                var sortType = $('#pagin_sort_type').val();
                var sortDirection = $('#pagin_sort_dir').val();
                var searchQuery = $('.coursesLookup').val();
                loadCourseListByParams(page,sortType,sortDirection,searchQuery);
            });
            $('.infoButton').click(function(){
                changeStatus(this.id, 1);
            });
            $('.plannedButton').click(function(){
                changeStatus(this.id, 2);
            });
            $('.playedButton').click(function(){
                changeStatus(this.id, 1);
            });
            $('.tableItem').click(function(){
                tableItemClick($(this).attr('lat'), $(this).attr('lng'), $(this).attr('cid'));
            });
            showRating();
            $('.deleteCourse').click(function(){
                var value = this.id;
                var arr = value.split('_');
                var cid = arr[2];
                deleteCourse(cid);
            });
            paginLinks();
        }
    });
    showRating();
}
function paginLinksProfile(){
    $('.pagin_first').click(firstClickProfile);
    $('.pagin_prev').click(prevClickProfile);
    $('.pagin_next').click(nextClickProfile);
    $('.pagin_last').click(lastClickProfile);
    $('.pagin_number').click(numClickProfile);
}
function paginLinks(){
    $('.pagin_first').click(firstClick);
    $('.pagin_prev').click(prevClick);
    $('.pagin_next').click(nextClick);
    $('.pagin_last').click(lastClick);
    $('.pagin_number').click(numClick);
}

function clearMarkers(){
    $('#map').gmap3(
    {
        action:'clear', 
        name:'marker', 
        tag:'search-results'
    });  
}
function nextClickProfile(){
    var val = $('#pagin_next_val').val();
    loadCourseListProfile(val);
}
function prevClickProfile(){
    var val = $('#pagin_prev_val').val();
    loadCourseListProfile(val);
}
function firstClickProfile(){
    var val = $('#pagin_first_val').val();
    loadCourseListProfile(val);
}
function lastClickProfile(){
    var val = $('#pagin_last_val').val();
    loadCourseListProfile(val);
}
function numClickProfile(){
    var val = this.id;
    val = val.replace('pagin_page_','');
    loadCourseListProfile(val);
}
function nextClick(){
    var val = $('#pagin_next_val').val();
    loadCourseList(val);
}
function prevClick(){
    var val = $('#pagin_prev_val').val();
    loadCourseList(val);
}
function firstClick(){
    var val = $('#pagin_first_val').val();
    loadCourseList(val);
}
function lastClick(){
    var val = $('#pagin_last_val').val();
    loadCourseList(val);
}
function numClick(){
    var val = this.id;
    val = val.replace('pagin_page_','');
    loadCourseList(val);
}
function loadPlannedCourses(clear){
    if(mapShowing == 'planned' && clear)
        return;
    if(clear)
        clearMap();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/getplanned",
        data: null,
        success: function(data){
            var result = JSON.parse(data);
            $.each(result, function(index, value) { 
                var parent = value['parent'];
                if(parent == 0)
                    parent = value['gid'];
                addPlannedMarker(value['latitude'], value['longitude'], parent);
            });
            mapShowing = 'planned';
            $('.mapPlayed').removeClass('mapPlayedActive');
            $('.mapAll').removeClass('mapAllActive');
            $('.mapPlanned').addClass('mapPlannedActive');
        //            showRating();
        }
    });
}
function loadPlayedCourses(clear){
    //    alert('played');
    if(mapShowing == 'played' && clear)
        return;
    if(clear)
        clearMap();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/getplayed",
        data: null,
        success: function(data){
            var result = JSON.parse(data);
            $.each(result, function(index, value) { 
                var parent = value['parent'];
                if(parent == 0)
                    parent = value['gid'];
                addPlayedMarker(value['latitude'], value['longitude'], parent);
            });
            mapShowing = 'played';
            $('.mapPlanned').removeClass('mapPlannedActive');
            $('.mapAll').removeClass('mapAllActive');
            $('.mapPlayed').addClass('mapPlayedActive');
        }
    });
}
function loadAllCourses(clear){
    if(mapShowing == 'all')
        return;
    clearMap();
    mapShowing = 'all';
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/getplanned",
        data: null,
        success: function(data){
            var result = JSON.parse(data);
            $.each(result, function(index, value) { 
                var parent = value['parent'];
                if(parent == 0)
                    parent = value['gid'];
                addPlannedMarker(value['latitude'], value['longitude'], parent);
            });
            $.ajax({
                type: "POST",
                url: baseDir + "ajax/getplayed",
                data: null,
                success: function(data){
                    var result = JSON.parse(data);
                    $.each(result, function(index, value) { 
                        var parent = value['parent'];
                        if(parent == 0)
                            parent = value['gid'];
                        addPlayedMarker(value['latitude'], value['longitude'],parent);
                    });
                    $('.mapPlanned').removeClass('mapPlannedActive');
                    $('.mapPlayed').removeClass('mapPlayedActive');
                    $('.mapAll').addClass('mapAllActive');
                //                     showRating();
                }
            });
        }
    });
}
function clearMap(){
    todo = {
        action:'clear'
    };
    todo['name'] = 'marker';
    $('#map').gmap3(todo);
}
function clearLast(){
    todo = {
        action:'clear'
    };
    todo['name'] = 'marker';
    todo['last'] = true;
    $('#map').gmap3(todo);
}
function mailInviteClick(){
    var email = $('#input_email').val();
    if(email.length < 1)
        alert('Please insert e-mail!');
    var message = $("#invite_message").val();
    //    if(message.length < 1)
    //        alert('Please insert message!');
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/mailinvite",
        data: {
            mail: $('#input_email').val()
        },
        success: function(data){
            if(data == 'OK')
                alert('Sent mail!');
            else
                alert(data);
        }
    });
}
function inviteClick(){
    $.ajax({
        url: baseDir + "popup/invite",
        dataType: "html",
        data: {
        },
        success: function( data ) {
            $('#sb-container').css('z-index','999');
            Shadowbox.open({
                content:    data,
                player: 'html',
                title:      " ",
                height:     450,
                width:      455,
                options: {
                    enableKeys: false,
                    onFinish: function(){
                        $('.closePopup').click(function(){
                            $('#sb-container').css('z-index','666999');
                            Shadowbox.close();
                        });
                        $('.closeBtnBox').click(function(){
                            $('#sb-container').css('z-index','666999');
                            Shadowbox.close();
                        });
                        $('.mailInvite').click(mailInviteClick);
                        $('.fbInvite').click(fbInviteClick);
                        $('.importClick').click(function(){
                            document.location = baseDir + 'index/invite/';
                        });
                    }
                }
            });
        }
    });
}
function tutorialClick(){    
    $.ajax({
        url: baseDir + "popup/tutorial",
        dataType: "html",
        async: false,
        data: {
        },
        success: function( data ) {
            Shadowbox.open({
                content:    data,
                player: 'html',
                title:      " ",
                height:     900,
                width:      1000,
                options: {
                    enableKeys: false,
                    onFinish: function(){
                        $('#sb-wrapper-inner').css('top','-100px');
                        $('.closePopup').click(function(){
                            Shadowbox.close();
                        });
                        $('.closeBtnBox').click(function(){
                            
                            Shadowbox.close();
                        });
                    }
                }
            });
        }
    });
}
function rateClick(){
    document.location = $('#facebook_fan_page_link').val();
    window.top.location.href = $('#facebook_fan_page_link').val();
}
function fbShareClick(message,pic){
    
    $.ajax({
        type: "POST",
        url: baseDir + "facebook/share.php",
        data: {
            pic:pic
        },
        success: function( data ) {
            alert('Posted to your wall!')
        }
    });
}
function fbInviteClick(){
    sendRequestViaMultiFriendSelector();
}

function sendRequestViaMultiFriendSelector() {
    FB.ui({
        method: 'apprequests',
        message: 'Come join me at Golfoon and build your personal golf map!'
    }, requestCallback);
}

function requestCallback(response) {
    
}

function shareClick(){
    
    $.ajax({
        url: baseDir + "popup/share",
        dataType: "html",
        data: {
        },
        success: function( data ) {
            Shadowbox.open({
                content:    data,
                player: 'html',
                title:      " ",
                height:     350,
                width:      550,
                options: {
                    enableKeys: false,
                    onFinish: function(){
                        $('.closePopup').click(function(){
                            Shadowbox.close();
                        });
                        $('.closeBtnBox').click(function(){
                            Shadowbox.close();
                        });
                        $('.emailShare').click(emailShareClick);
                        $('.fbShare').click(function(){
                            fbShareClick('s',$(this).attr('f_pic'));
                        });
                    }
                }
            });
        }
    });
}
function hideLoading(){
    $("#loadingImg").hide();
    $('.multiCourseLink').css('left','6px');
}
function showLoading(){
    $("#loadingImg").show();
    $('.multiCourseLink').css('left','-15px');
}
function searchw(){
    //@todo !!!
    hideLoading();
    var query = $('#favGolfCourse').val();
    if(query.length <= 3)
        return;
    
    showLoading();
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/searchw",
        data: {
            query:query
        },
        success: function(data){
            hideLoading();
            $("#searchdivwelcome").html(data);
            $('.resultRow').click(function(){
                document.location = baseDir + '?cid=' + $(this).attr('cid');
            });
        }
    });
}
function search(){
    //@todo !!!
    hideLoading();
    var query = $('.courseInput').val();
    if(query.length <= 3)
        return;
    showLoading();
    //    if(ajaxReq != 'undefined')
    //        ajaxReq.abort();
    
    ajaxReq = $.ajax({
        type: "POST",
        url: baseDir + "ajax/search",
        data: 'query='+query,
        success: function(data){
            hideLoading();
            $("#searchdiv").html(data);
            
            clearMarkers();
            $('.resultRow').each(function(index, value){
                //                alert($(value).attr('lat'));
                addNeutralMarker($(value).attr('lat'), $(value).attr('lng'), $(value).attr('cid'));
            });
            
            $('.resultRow').click(function(){
                tableItemClick($(this).attr('lat'), $(this).attr('lng'), $(this).attr('cid'));
                $("#searchdiv").html('');
            });
            $('body').click(function(){
                $("#searchdiv").html('');
            });
            $('.courseInput').live('keydown',function(){
                $("#searchdiv").html('');
            });
            $('.courseNotFound').click(reportClick);
            scroll(0,200);
        }
    });
}
function playedClick(){
    //@todo !!!
    loadPlayedCourses(true);
//    alert('Played courses filter');
}
function plannedClick(){
    //@todo !!!
    loadPlannedCourses(true);
//    alert('Planned courses filter');
}
function allClick(){
    loadAllCourses();
//    alert('All courses filter');
}
function reportClubClick(){
    //@todo !!!
    var clubName = $('.boxHeader').html();
    var courseName = $('.boxSubHeader').html();
    $('.clubNameModal').html(clubName);
    $('.courseNameValue').val(clubName);
    $('#reportclub').dialog("open");
//    alert(clubName + '/'+ courseName);
}
function reportCourseClick(){
    //@todo !!!
    var clubName = $('.boxHeader').html();
    var courseName = $('.boxSubHeader').html();
    $('.clubNameModal').html(clubName);
    $('.courseName').html(courseName);
    $('.courseNameValue').val(courseName);
    $('#reportcourse').dialog("open");
//    alert(clubName + '/'+ courseName);
}
function reportClick(){
    //@todo !!!
    //    var clubName = $('.boxHeader').html();
    //    var courseName = $('.boxSubHeader').html();
    $('#reportmissing').dialog("open");
//    alert('Report missing course screen : Waiting for integration of support system.');
}
function alernativeReport(){
    $('#alternativereport').dialog("open");
    
}
function logout(){
    FB.api('/me', function(response) {
        $.ajax({
            type: "POST",
            url: baseDir + "member/logout",
            async:false,
            data: null,
            success: function(data){
                if(data == 'OK'){
                    document.location = baseDir;
                }
            }
        });
    });
}
function setBackgroundImages(){
    var iu = baseDir + '/skins/default/';//Images url
    $('.topHeaderPart').css('background-image','url("'+iu+'images/loginBg.jpg")');
    $('.questionMark').css('background-image','url("'+iu+'images/questionMark.gif")');
    $('#footer').css('background-image','url("'+iu+'images/footer.jpg")');
    $('.courseSubmit').css('background-image','url("'+iu+'images/searchInputFirst.gif")');
    $('.coursesLookupSubmit').css('background-image','url("'+iu+'images/zoomImage.gif")');
    $('.sorting').css('background-image','url("'+iu+'images/datatable/sort_both_w.png")');
    $('.playedButton').css('background-image','background: url("'+iu+'images/datatable/buttonPlayedSR.png")');
    $('.deleteCourse').css('background-image','background: url("'+iu+'images/delete.png")');
    //    $('.paginate_button').css('background-image','url("ui-lightness/images/ui-bg_glass_65_e6e6e6_1x400.png")');
    $('.holesNum').css('background-image','url("'+iu+'images/greenSmallBg.gif")');
    $('.plannedText').css('background-image','url("'+iu+'images/greenSmallBg.gif")');
    $('.currentHole').css('background-image','url("'+iu+'images/yellowSmallBg.gif")');
    $('.account_button').css('background-image','url("'+iu+'images/ranking_button.png")');
    $('.contentLoginBg').css('background-image','url("'+iu+'images/loginBg.jpg")');
    $('#facebookConnect').css('background-image','url("'+iu+'images/fbConnect.jpg")');
    $('#appDescription').css('background-image','url("'+iu+'images/play.png")');
    $('#favCourseHolder').css('background-image','url("'+iu+'images/transparentBg.png")');
    $('.closeBtnBox').css('background-image','url(".'+iu+'images/closeButton.png")'); 
    $('.clubBoxClubbleStatus').css('background-image','url("'+iu+'images/buttonPlayedSR.png")');
    $('.clubBoxQuestionmark').css('background-image','url("'+iu+'images/question_mark1.png")');
    $('.clubBoxImageHolder').css('background-image','url("'+iu+'images/clubbleImageBackground.png")');
    $('.mapPlayedActive').css('background-image','url("'+iu+'images/map_played_down.png")');
    
    /*OVO SREDI*/
    $('.mapPlayed').css('background-image','url("'+iu+'images/map_played_up.png")');
    $('.mapPlayed:hover').css('background-image','url("'+iu+'images/map_played_down.png")');
    $('.mapPlanned').css('background-image','url("'+iu+'images/map_planned_up.png")');
    $('.mapPlanned:hover').css('background-image','url("'+iu+'images/map_planned_down.png")');
    /*OVO SREDI*/
    
    $('.mapPlannedActive').css('background-image','url("'+iu+'images/map_planned_down.png")');
    $('.mapAll').css('background-image','url("'+iu+'images/map_all_up.png")');
    $('.mapAll:hover').css('background-image','url("'+iu+'images/map_all_down.png")');
    $('.mapAllActive').css('background-image','url("'+iu+'images/map_all_down.png")');
}
function showGreenKeeperText(){
    
}
function hideGreenKeeperText(){
    
}
function shareToWall(message, name, description, link, picture, caption){
    //    alert('Sharing to wall...')
    var params = {};
    params['message'] = message;
    params['name'] = name;
    params['description'] = description;
    params['link'] = link;
    params['picture'] = picture;
    params['caption'] = caption;
    FB.api('/me/feed', 'post', params, function(response) {
        if (!response || response.error) {
        //            alert('Error occured!');
        } else {
    //            alert('Shared!')
    }
    });
//            alert('Done!')
}

function RATING_ACTIONS(){
    $('#topgolfooniesselect').unbind('change');
    $('#topgolfooniesselect').change(function(){
        var value = $(this).val();
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/ranking",
            data: { 
                type: 1,
                value: value
            },
            success: function( data ) {
                $('#topgolfoonieslist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    
    $('#mostplayedcoursesselect').unbind('change');
    $('#mostplayedcoursesselect').change(function(){
        var value = $(this).val();
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/ranking",
            data: { 
                type: 2,
                value: value
            },
            success: function( data ) {
                $('#mostplayedlist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    $('#bestratedcoursesselect').unbind('change');
    $('#bestratedcoursesselect').change(function(){
        var value = $(this).val();
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/ranking",
            data: { 
                type: 3,
                value: value
            },
            success: function( data ) {
                $('#bestratedlist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    $('#topgolfooniessearchbtn').unbind('click');
    $('#topgolfooniessearchbtn').click(function(){
        var query = $('#topgolfooniessearchinput').val();
        var count = $('#topgolfooniesselect').val();
        var type = 1;
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/rankingsearch",
            data: { 
                query:query,
                count:count,
                type:type
            },
            success: function( data ) {
                $('#topgolfoonieslist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    $('#mostplayedsearchbtn').unbind('click');
    $('#mostplayedsearchbtn').click(function(){
        var query = $('#mostplayedsearchinput').val();
        var count = $('#mostplayedcoursesselect').val();
        var type = 2;
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/rankingsearch",
            data: { 
                query:query,
                count:count,
                type:type
            },
            success: function( data ) {
                $('#mostplayedlist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    $('#bestratedsearchbtn').unbind('click');
    $('#bestratedsearchbtn').click(function(){
        var query = $('#bestratedsearchinput').val();
        var count = $('#bestratedcoursesselect').val();
        var type = 3;
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/rankingsearch",
            data: { 
                query:query,
                count:count,
                type:type
            },
            success: function( data ) {
                $('#bestratedlist').html(data);
                RATING_ACTIONS();
            }
        });
    });
    $('#friendsrankingsearchbtn').unbind('click');
    $('#friendsrankingsearchbtn').click(function(){
        var query = $('#friendsrankingsearchinput').val();
        var count = 0;
        var type = 4;
        $.ajax({
            type: "POST",
            url: baseDir + "ajax/rankingsearch",
            data: { 
                query:query,
                count:count,
                type:type
            },
            success: function( data ) {
                $('#friendsrankinglist').html(data);
                RATING_ACTIONS();
            }
        });
    });
}

function doTheSharingStuff(){
    if($('#postedonfb').val() == 1)
        return;
    
    window.fbAsyncInit = function() {
        FB.init({
            appId   : facebookAppId,
            status  : true,
            cookie  : true,
            xfbml   : true,
            oauth: true
        });
        FB.Canvas.setSize({
            width: 680, 
            height: 1850
        });
        
        FBLoaded = true;
        //        loginWithFacebook();
        FB.Canvas.setAutoResize();
        FB.getLoginStatus(function(response) {
            if (response.authResponse) {
                //                    alert('Heck, I am loged in with facebook. What are you talking about!?');
                shareToWall(
                    $('#fbmessage').val(), 
                    'Golfoon', 
                    'Golfoon is a free app that allows me to track where I have played golf.', 
                    baseDir, 
                    $('#fbimgsrc').val(), 
                    'Build your own Golf map.'
                    );
                if(!loggedIn) {
                    fbJSLoggedIn = true;
                }
            } else {
        //                logout();
        }
        });
    };
}

function stopedLooking(){
    $.ajax({
        type: "POST",
        url: baseDir + "ajax/stopedlooking",
        data: null,
        success: function( data ) {}
    });
}
$(function(){
    $('.invite').click(inviteClick);
    $('.share').click(shareClick);
    $('.tutorial').click(tutorialClick);
    $('.rate').click(rateClick);
    $('.logout').click(logout);
    $('.reportLink').click(reportClick);
    $('.courseSubmit').click(search);
});
