// Ajax Contents Library
// By Laureano Martin Arcanio
// 05/10/2009
// larcanio@gmail.com

// Images Uploader 

var data = {'sql_SelfID': 0, 'sql_Type': 'photo_save', 'ContentType': 'none', 'URL': false, 'ContentID': 0};
var photo_ids = Array();

clicked = '';


var locations = Array();
var location_names = Array();
var activities = Array();
var activity_names = Array();






function inArray(value, array, index) {
	//index=false;
	for (var i=array.length-1; i>=0; --i ){
		splited = array[i].split('-');
		if (array[i] == value || value == splited[0] || value == splited[1] ) {
			if (index != true) {
				return true;
			}
			else{
				return i;
			}
		}
	}
	return false;
}

function getLocations(find) {
    $.getJSON(
        "/content/data/related_locations.php", 
        { action: "getLocations", find: find }, 
        function(json) {
            locations = json;
            i = 0;
            $.each(json, function (item, value) {
                location_names[i] = item;
                i++;
            })
     });
}

function getActivities(find) {
    $.getJSON(
        "/content/data/related_locations.php", 
        { action: "getActivities", find: find }, 
        function(json) {
            activities = json;
            i = 0;
            $.each(json, function (item, value) {
                activity_names[i] = item;
                i++;
            })
     });
}

function tabsMenuStyle(Type) {
    // Changes the Tab images on tab item change

    if (Type == 'undefined') 
        Type = 'articles';
       
    $("#tab-menu-a-l-p-holder .menu-item").each(function() {

        var classes = $(this).children().attr('class');
        classes = classes.split(' ');
        var class_t = classes[1];
        //alert(class);
        
        var  show = "back";
        var color = "#FFFFFF" // Blanco
        if (class_t == Type && Type != 'none') {
            show = 'front';   
            color = "#000000" // negro 
        }
        
        // Exeption for photos
            // Change Articles too
        if (Type == 'photos') {
            if (class_t == 'articles') {
                show = 'back_exception';
            }
        }
        
        var image = "url(/content/images/" + class_t + "_" + show + ".jpg)" ;
        $(this).css({'background-image': image});
        $(this).children().css({'color': color});
    });
}



function resizeVideo() {
    // Resize video to  given Widht and Height
    // Conserve aspect ratio
    // Get current values
    
    var s_widht = 354;
    var s_height = 315;
    
    var widht = $('embed').width();
    var height = $('embed').height();
    // Calculates new height
    
    // Resize height    
    if (widht > s_widht) {
        height = s_widht * height / widht;
        widht = s_widht;
    }
    
    // Resize widht
    if (height > s_height) {
        widht = s_height * widht / height;
        height = s_height;
    }    
    

//    
//    alert(height);
//    alert(widht);


    $('.article-comments-content-main embed').width(widht);
    $('.article-comments-content-main embed').height(height);
}

function updateRelated() {
    // Related Selectors
    
    // If Location and Activities not loaded then load
    if (locations.length == 0)
        getLocations('');
    if (activities.length == 0)
        getActivities('');
    
    defaultTags();
    
    $("#LocationsName").autocomplete(location_names);
    
    $("#LocationsName").result(function(event, data, formatted) {
        if ($(this).val() != '' && $(this).val != 'select location') {
            var activity_ur = $("#ActivityName").val();
            
            if (activity_ur) {           
                append = true;
                $("#related-tags-display .selected-location").each(function (index, object) {
                    text = $(this).text();               
                    arr = text.split(': ');
                                                           
                    if (data == arr[0]) {
                        //alert(data);
                        exist = false;
                       
                        temp = arr[1].split(" (");
                        arr[1] = temp[0];
                        
                        activities_ = arr[1];
                        
                        if (activities_.indexOf(', ') != -1) {
                            activities_ = arr[1].split(', ');
                            
                            if (inArray(activity_ur, activities_, false) == true) { 
                                exist = true;
                                //alert('multi');
                            }
                        } else {
                            
                            if (activities_ == activity_ur) {
                                exist = true;
                                //alert('one');
                            }
                        }
                        
                        text = '';
                        if (exist != true) {
                        
                            $text = arr[1] + ", " + activity;
                            $(this).remove();
                            html = "<span  class='selected-location'>" + data + ": " + arr[1] + ", " + activity_ur  + " (<a href='#' class='remove-tag'>Remove</a>)</span>";
                            $("#related-error").text('');  
                            $("#related-tags-display").append(html);
                            found = false;
                            append = false;
                        } else {
                            $("#related-error").text('You have already added these tags');
                            found = true;
                            append = false;

                        }
                        
                        found = true;
                    } else {
                        // Not Location
                        found = false;
                    
                    }
                });
                
                if ($("#related-tags-display .selected-location").length == 0 || append == true) {
                    html = "<span class='selected-location'>" + data + ": " + activity_ur + " (<a href='#' class='remove-tag'>Remove</a>)</span>";
                    $("#related-error").text('');
                    $("#related-tags-display").append(html);
                }
                
                $(this).val('');
                $("#ActivityName").val('select activities');
                $("#ActivityName").focus();
                
                // Adds delete event on clicking the <a>
                if ($(".remove-tag").length !=0) {
                    $(".remove-tag").click(function () {
                        $(this).parent().remove();
                        return false;
                    }); 
                }   
            }
        } else {
            $(this).focus();
        
        }
    });
    
    $("#ActivityName").autocomplete(activity_names);
    
    $("#ActivityName").result(function(event, data, formatted) {
        $("#LocationsName").focus();
        $("#LocationsName").val('');
    });
    
    $("#LocationsName").keyup(function(e) {
	    //alert(e.keyCode);
	    if(e.keyCode != 13) {
		    if ($("#ActivityName").val() == '' || $("#ActivityName").val() == 'select activities') {
		        $(this).val('');
		        $("#ActivityName").focus();
		    }
	    }
    });
}

function getRelated() {
    // Retrieves elements from DOM and builds LocationID#ActivityID#ActivityID# strings
        
    if ($(".selected-location").length !=0) {
         var values_ = Array();
         $.each($(".selected-location"), function (index, tag) {
            var text = $(this).text();
            
            
            var arr = text.split(': ');
            
            
            var temp = arr[1].split(" (");
            arr[1] = temp[0];
            //alert(arr[1]);             
            if (arr[1].indexOf(', ') == -1) {
                var tag =   locations[arr[0]]+ "#" + activities[arr[1]];
            } else {
                cont = arr[1].split(", ");
                var tag = locations[arr[0]];
                for (i = 0; i<=(cont.length-1); i++) {
                    join = '#';
                    if (i != 0)
                        join = "-"; 
                    tag += join + activities[cont[i]];
                }           
            }           
            values_[index] = tag;
         });
        return values_;
    } else {
    
        return false;
    }
}


function defaultTags() {

    // Display Default tags for Current Location
    if ($("#field").length != 0) {
        if ( $("#field").val() == 'LocationID') {
             
           html = '';
           for (l_name in locations) {
                if ($("#value").val() == locations[l_name]) {
                    html = "<div id='related-tags-default'><span class='selected-location-default'>" + l_name; 
                }
                
            }
            for (a_name in activities) {
                if ($("#activity").val() != '') {
                        if ($("#activity").val() == activities[a_name]) {
                            html += ": " + a_name;
                        } 
                    }
                }
            
            if (html) {
                html += " (<a href='#' class='remove-tag'>Remove</a>)</span></div>";
                $("#related-tags-default").remove();
                $("#related-tags-display").append(html);
                if ($(".remove-tag").length !=0) {
                    $(".remove-tag").click(function () {
                        $(this).parent().remove();
                        return false;
                    }); 
                }               
            }
        }
    }
}

function ifExist(element) {
    // Check if an Element Exist
    if (element.length > 0)
        return true;
    else
        return false;
    
}


function ifLogged() {
    if (ifExist($(".login-message")) == true) {
        // User Not Logged IN
        // alert('Not logged');
        LogIN_LogOut('disabled');
        return false;
    }
    else {
        // User Logged In
        // alert("Logged In");
        LogIN_LogOut('enabled');
        return true;
    }

}

function LogIN_LogOut(login) {
    if (ifExist($(".content-form")) == true) { 
        if (login == 'disabled') {
            $(".content-form input").attr('disabled', login);
            $(".content-form textarea").attr('disabled', login);
        } else {
            $(".content-form textarea").removeAttr('disabled');
            $(".content-form input").removeAttr('disabled');
        }
    }

}



function UpdateDOM(html, values) {
    photo = 0;

    if (values['Type']== 'photos') {
        photo = 1;
        type = 'photos';
    }
    if (values['Type']== 'news_events') {
        photo = 1;  
        type = 'news_events';
    }
    
    if (photo == 1) {
        //alert('true');
        if (ifExist($('#upload'))) {
            data = {'sql_SelfID': 0, 'sql_Type': 'photo_save', 'ContentType': type, 'URL': false, 'ContentID': 0};
            UploadPhoto();
            updateGallery();
        }
    }
    
    
    if (values['Type']== 'ratings') {
        Rate();
    }



    $(".hidden-image").hide();
    $(".art-reply-input").hide();
    $("#art-photo-details").hide();
    photoDescription();
    photo_ids = Array();
    
    $("#art-photo-details").hide();
    
    $(".art-template-holder-comments").fadeIn('slow', function() {
        resizeVideo();
    });
    
    // Set Page for content Request
    $(".page-item").click(function () {
        var CustomerID = $('#ProfileCustomerID').val();
        var page = $(this).text();
        $('#page').val(page);
        requestContent_Paginate(values['Type'], '', '', CustomerID);
        return false;
    });
    
    $('#search-content').click(function () {
        $(this).val('');
        return false;
    })
    
    $('#search-content').blur(function () {
        if ($(this).val() == '') {
            $(this).val('Free search');
        }
    })
    
    $(".search-button-content").unbind();
    $(".search-button-content").click(function () {
        //var page = $(this).text();
        var CustomerID = $('#ProfileCustomerID').val();
        //$('#page').val(page);
        requestContent_Search(values['Type'], '', '', CustomerID);
        return false;
    })

	$(".search-tag-link").unbind();
    $(".search-tag-link").click(function () {
		$(".search-button-content").click;
		$("#search-content").val() = $(".search-tag-link").val();
    })
    
    $(".next").click(function () {
       var page = $(".page-number-selected a").text(); 
       var next = parseInt(page) + 1;
       var CustomerID = $('#ProfileCustomerID').val();
       $('#page').val(next);
       //alert($.dump(values));
       requestContent_Paginate(values['Type'], '', '', CustomerID);
       return false;
    });
    
    $(".previous").click(function () {
       var page = $(".page-number-selected a").text(); 
       var next = parseInt(page) - 1;
       var CustomerID = $('#ProfileCustomerID').val();
       $('#page').val(next);
       requestContent_Paginate(values['Type'], '', '', CustomerID);
       return false;
    });
    
    // Taging boxes text
    $('.related-imput').click(function () {
        $(this).val('');
        return false;
    })
    
    $('.related-imput').blur(function () {
        if ($(this).val() == '') {
            if ($(this).attr('id') == "ActivityName") {
                $(this).val('select activities');
            } else {
                $(this).val('select location');
            }
        }
    })
    
    
      
    // Shows hide seatch box
    if (values['Type'] == '' || values['Type'] == 'none') 
        $("#tab-menu-a-l-p-bar-search div").hide();
    else 
        $("#tab-menu-a-l-p-bar-search div").show();
    
    // Change the tab
    tabsMenuStyle(values['Type']);
    updateRelated();   
    ifLogged();
    
    return true;
}

function Rate(){
    $('.hover-star').rating({
        focus: function(value, link){
            var tip = $('#hover-test');
            tip[0].data = tip[0].data || tip.html();
            tip.html(link.title || 'value: '+value);
        },
            blur: function(value, link){
            var tip = $('#hover-test');
            $('#hover-test').html(tip[0].data || '');
        }
    })
}


function updateGallery() {
    // Creates a gallery for each Photo album
    $('.photo-gallery').each(function(obj) {
        object = '#' + this.id + ' a[@rel*=lightbox]';
        $(object).lightBox({fixedNavigation:true});
    });
}

function UpdateDOM_on_Upload(html) {
    // Change the tab
    photoDescription();
    resizeVideo();
    $(".hidden-image").hide();
    $("#art-photo-details").hide();
}

function LoadContent(values, url) {
// Executes a POST request then update the content lists
//   $(".art-template-holder-comments").hide();
     $(".art-template-holder-comments").empty().html('<div id="content-loading" style="position: relative; left: 42%; width: 66px;"><img src="/content/images/ajax-loader.gif" /></div>');

    $(".art-template-holder-comments").load(   
        url , 
        values, 
        function(html) {
            // Updates the List of Contents
            //alert($.dump(values));
            response = UpdateDOM(html, values);
            
        }
    );
}

function requestContent(ContentType, Locations, Activities, CustomerID ) {
    // Builds an object from given Content Types and request sontents
    
    // Let click only one time the same tab
    if (clicked != ContentType) {
        clicked = ContentType;
      
        if (CustomerID == 'undefined')
            CustomerID = 0;
            
        var values = {'Type': ContentType, 'CustomerID': CustomerID, 'Locations': '', 'Activities': ''};
//        
        // Set Location Type from gloval variable setted in a input 
        

        
        
        var field = $("#field").val();
        var value = $("#value").val();
        var activity = $("#activity").val();
        
        values[field] = value;
        
//        alert(values);
        
       if  (ContentType == 'reviews' || ContentType == 'reviews_tribe_home') {
            //var activity = $("#rating-activity").attr('activity');
            values['ActivityRating'] = Activities;
       }
        
        if (activity != '')
            values['ActivityID'] = activity;
        
        if ($("#customer-profile-flag").length >0) {
            values['Profile'] = 1;
            //alert($.dump(values));
        }
        //alert($.dump(values));
        var url = "/content/list_contents.php";
            
        // Made ajax request and upload
        LoadContent(values, url);
        
        
    }
}

//-- Request Contents

function requestContent_Paginate(ContentType, Locations, Activities, CustomerID ) {
    // Builds an object from given Content Types and request sontents
    // PAgination and Search boxes
    
    if (CustomerID == 'undefined')
        CustomerID = 0;
   
    clicked = ContentType;

    var page = $("#page").val();
    

   

    values = {'Type': ContentType, 'CustomerID': CustomerID, 'Page': (page-1), 'Locations': '', 'Activities': ''} //,'FreeSearch': search};
       
    if ($("#customer-profile-flag").length >0) {
        values['Profile'] = 1;
    }
    
    
    
    if ($("#search-keyword").length >0) {
        var search = $("#search-keyword").val();
        values['FreeSearch'] = search;
    }
    
    
    
    // Set Location Type from gloval variable setted in a input 
    var field = $("#field").val();
    var value = $("#value").val();
    var activity = $("#activity").val();
    
    values[field] = value;
    
    if (activity != '')
        values['ActivityID'] = activity;
    
    if ($("#customer-profile-flag").length >0) {
        values['Profile'] = 1;
        //alert($.dump(values));
    }
    //alert($.dump(values));
    var url = "/content/list_contents.php";
    

    //alert($.dump(values));
    LoadContent(values, url);

}

function requestContent_Search(ContentType, Locations, Activities, CustomerID ) {
    // Builds an object from given Content Types and request sontents
    // PAgination and Search boxes
    
    if (CustomerID == 'undefined')
        CustomerID = 0;
   
    clicked = ContentType;

    values = {'Type': ContentType, 'CustomerID': CustomerID, 'Page': 0, 'Locations': '', 'Activities': ''} //,'FreeSearch': search};
    
    if ($("#search-content").length >0) {
        var search = $("#search-content").val();
        values['FreeSearch'] = search;
    }
    
    if ($("#customer-profile-flag").length >0) {
        values['Profile'] = 1;
    }
    
    
    // Set Location Type from gloval variable setted in a input 
    var field = $("#field").val();
    var value = $("#value").val();
    var activity = $("#activity").val();
    
    values[field] = value;
    
    if (activity != '')
        values['ActivityID'] = activity;
    
    if ($("#customer-profile-flag").length >0) {
        values['Profile'] = 1;
        //alert($.dump(values));
    }
    //alert($.dump(values));
    var url = "/content/list_contents.php";
    

    //alert($.dump(values));
    LoadContent(values, url);

}


// Slide Show effects
function showReply(id) {
    //alert(id);
    $(id).slideToggle(600);
}

// Submit Contents
function submitContent(object, Type) {
    // Submits and create new content by Ajax
    
    var values = $(object).serialize();
    
    var value = $("#value").val();
    var field = $("#field").val();
    
    values += "&" + field + "=" + value;
    values += "&ActivityID=" + $("#activity").val();
    
    
    if (object == "#photo_form" || object == "#news_form") {
        // Build Photo IDS
        if (photo_ids) {
            str = photo_ids.join(', ');
            values += "&PhotoID=" + str;
            
        }

        
    }
    photo_ids = Array();
    
    // Related Tags
//    var tags = getRelated();
//    tag_str = '';
//    if (tags) {
//        for (i=0; i<=tags.length-1; i++) {
//            tag_field = "&Tag_" + i;
//            tag_str += tag_field + "=" + tags[i];
//        }

//    }
//    
//    if (tag_str != '') {
//        values += tag_str;
//    }
    
    //alert($.dump(values));
    if ($("#customer-profile-flag").length >0) {
        values['Profile'] = 1;
        //alert($.dump(values));
    }
    
    //alert(values);
    var url = "/content/data/content.php";
    //$(".article-comments-holder").hide();
    
    
//    alert(values);



    $.ajax({
        type: "POST",
        url: url,
        data: values,
        success: function(html){
            //alert(html);
            $(".art-template-holder-comments").remove();
            $("#tab-menu-a-l-p-holder").after(html);
            $(".art-template-holder-comments").hide();
            $(".art-reply-input").hide();
            // Updates the List of Contents
            UpdateDOM(html, {'Type': Type});
        }
    });
    return false;
}

// -- Submit Contents

// sql_Type = photo_save
// sql_SelfID = 0
// URL 

function UploadPhoto(){  
    var btnUpload=$('#upload');  
    var status=$('#status');  
    new AjaxUpload(btnUpload, {  
        action: '/content/data/content.php',  
        data: data,
        //Name of the file input box  
        name: 'Image_1',  
        onSubmit: function(file, ext){  
            
            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                // check for valid file extension  
                status.text('Only JPG, PNG or GIF files are allowed'); 
                
                return false;  
                
            }  
            
            if (data['ContentType'] == 'news_events') { 
            
                if (data['ContentID'] != 0 ) {
                    $(".button-upload").text('You have already uploaded a photo !');   
                    return false;
                }
            }
            
            status.text('Uploading...');  
        },  
        onComplete: function(file, response){ 
            flag = 0; 
            if (data['sql_SelfID'] == 0) {
                flag = 1;
            }
            
            
            if(response != "error")
                eval(response);
                photo_ids.push(data['ContentID']);
                
                
                
               
            //alert($.dump(photo_ids));
            
            // Set Parent ID to form commit
            if (flag==1) {
                $("#ParentID").val(data['sql_SelfID']);
            }
            
            //alert(response);
            
            UploadPhoto();
            
            //On completion clear the status  
            status.text('');  
            
            //Add uploaded file to list  
            if(response != "error") {  
                // HTML for Thumbnails container
                html =      "   <div class='thumb-container'>";
                html +=     "      <div class='thumb-photo'>";
                html +=     '           <img class="image" src="'+ data['URL']+'" alt=""' + 'ContentID="'+ data['ContentID'] + '"/>'
                html +=     "      </div>";
                html +=     "      <div class='thumb-title'>";
                html +=     "           <label> Image Caption</label>";
                html +=     '           <textarea name="'+data['ContentID'] + '-sql_Image_1_Caption" id="d_sql_Image_1_Caption" size="20" cols="15"></textarea><br/>';
                html +=     "      </div>";
                html +=     "   </div>" ;
                
                $('<li></li>').appendTo('#files').html(html).addClass('success');  
            } else{  
//                $('<li></li>').appendTo('#files').text("Image not properly saved !").addClass('error'); 
                //$(".login-message").append("You are not Logged In, please log in <a href='/community/'>Here</a> !"); 
                
                $("#art-photo-input-mid .login-message").remove();
                $("#art-photo-albun").after("<span class='login-message'>You are not Logged In, please log in <a href='/community/'>Here</a> ! </span>")
                //alert(response);
            }  
            
            // Update DOM for javascript events
            UpdateDOM_on_Upload();
         }  
     });  
 } 

// -- Images Uploader

function photoDescription() {
    $(".image").click(function() {
        showReply("#art-photo-details");
        $("#d_ContentID").val($(this).attr('ContentID'));
    });
}

$(document).ready(function() {
    // Hide reply Form
       
    //UpdateDOM('', {'Type': 'none'});
    $(".art-reply-input").hide();    
    $("#art-photo-details").hide();
});

